I'm trying to use tkinter to make an options dialog for my Python program, and I want to add some of the refinements that most GUI programs have. Specifically, I want my options to have what tk calls "accelerator keys" - but tk's method of defining these only works on menus; for things like buttons and "checkbuttons", I can specify a character in the button text to underline, signifying the accelerator key to use, but I can't get the code to actually perform the action that would occur if the user used the mouse instead. My "invoke" commands are being flagged with error messages in the console, and I don't know why. What's wrong in the example below? (I know, probably lots of things - I'm still learning.)
# -*- coding: utf-8 -*-
import Tkinter as tk
def main():
print("Program started")
my_dlg_bx = tk.Tk()
def ckbtn_action():
if tk_ckbtn_var.get():
print("checkbox was changed to checked")
else:
print("checkbox was changed to UNchecked")
tk_ckbtn_var = tk.BooleanVar()
tk_ckbtn = tk.Checkbutton(my_dlg_bx,
command = ckbtn_action,
offvalue = False,
onvalue = True,
text = "Press C to check the box",
underline = 6,
variable = tk_ckbtn_var,
)
tk_ckbtn.pack()
my_dlg_bx.bind("<KeyPress-c>", tk_ckbtn.invoke) # TypeError: invoke() takes exactly 1 argument (2 given)
my_dlg_bx.attributes("-toolwindow", True)
my_dlg_bx.attributes("-topmost", True)
my_dlg_bx.resizable(width = False, height = False)
my_dlg_bx.focus_force()
my_dlg_bx.mainloop()
print("Program ended")
main()
The problem is with .invoke
not taking arguments other than self
,
and bind
expecting the callback function to take an Event instance as an argument, which tk_cktn.invoke
does not do
To make it work we can just use a lambda
(or equivalently a function) to take the event argument and then call tk_ckbtn.invoke()
:
my_dlg_bx.bind("<KeyPress-c>", lambda event: tk_ckbtn.invoke())
Then it should all work as intended
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments