I'm a python beginner.
Using Button on tkinter, I am trying to create a program where the window disappears after storing different variables (True, False) depending on the button I click (OK, cancel).The movement is like messagebox's askokcancel.
Normally, I would use messagebox, but I wanted to include hyperlinks in the dialog, so I made it with Button as follows.
This is the main topic, but with this source, the return buff will be returned as True no matter which button you press.It seems that it will not be possible to store it in BooleanVar after destroyed.
If you turn off destroy, the return value will change depending on the button, but of course the frame will not disappear.
Could you please let me know if there is a good way to make them coexist?
Python 3.5.2::Anaconda 4.0.0 (32-bit)
Tcl/Tk 8.6
That's it.
import tkinter ask
import webbrowser
def hyperlink (event):
webbrowser.open_new(event.widget.cget('text'))
def program_start():
root.destroy()
return lambda:buff.set(True)
def program_quit():
root.destroy()
return lambda:buff.set(False)
root=tk.Tk()
buff=tk.BooleanVar()
buff.set (True)
lbl=tk.Label (root, text=r'https://google.co.jp', fg="blue", cursor="hand2")
lbl.pack()
lbl.bind("<Button-1>", hyperlink)
tk.Button(root, text='OK', width=10, command=program_start).pack()
tk.Button(root, text='cancel', width=10, command=program_quit).pack()
root.mainloop()
print(buff.get())
As far as the reference, callback doesn't seem like a lambda formula in the first place...
As a solution, isn't it possible to do destroy
after set
?
def program_start():
buff.set (True)
root.destroy()
def program_quit():
buff.set (False)
root.destroy()
Then
If you turn off destroy, the return value will change depending on the button.
Assuming that erasing destroy is equivalent to commenting out root.destroy()
, wouldn't the code that is set
simply return as part of the lambda formula?I don't actually reproduce it on hand.
If it is classified and reused, I think I can write it like this.
import tkinter ask
import webbrowser
classMsgBox():
def__init__(self):
self.root=tk.Tk()
self.ret = False
lbl=tk.Label(self.root, text=r'https://google.co.jp',fg="blue", cursor="hand2")
lbl.pack()
lbl.bind("<Button-1>",self.hyperlink)
tk.Button(self.root,text='OK',width=10,command=lambda:self.root_exit(True))).pack()
tk.Button(self.root,text='cancel',width=10,command=lambda:self.root_exit(False))).pack()
def hyperlink (self, event):
webbrowser.open_new(event.widget.cget('text'))
def start (self):
self.root.mainloop()
def root_exit(self, state):
self.ret=state
self.root.destroy()
default(self):
return self.ret
msg_box=MsgBox()
msg_box.start()
print(msg_box.ret)
© 2024 OneMinuteCode. All rights reserved.