使用字典的python 3.4按钮命令不起作用


from tkinter import *
root = Tk()
def But_Cmd(butcode):
global Button_select, frame1, b1, b2
def But_dic_lookup():    
    try:    
        Button_select[butcode]()
    except:  
        print('*** button select not found, butno= ', butcode)      
    return(But_dic_lookup)   
return
#===========================================================================
def Proc_button_100():
    print('Proc_button_ 100') 
    return 
def Proc_button_101():
    print('Proc_button_ 101')
    return 
def Proc_button_102():
    print('Proc_button_ 102')
    return 
def Proc_button_103():
    print('Proc_button_ 103')
    return 
#--------------------------------------------------------------------------     
def Button_Dict():
    global Button_select
    Button_select = {
        100: Proc_button_100,
        101: Proc_button_101,
        102: Proc_button_102,
        103: Proc_button_103,
    } 
    return  
#--------------------------------------------------------------------
def List_Dic():
    for keys,values in Button_select.items():
        print(keys)
        print(values)
    return
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++  
#global Button_select, frame1, b1, b2
Button_Dict()    
List_Dic()
root.geometry("400x200+00+00") 
frame1 = Frame(root)
frame1.config(background= 'silver')
frame1.place(x = '00', y = '00', width = '400', height = '200' )
frame1.pack_propagate(0) 
b1 = Button(frame1, text='pusch1', command = But_Cmd('100'))
b1.config(background= 'orange')
b1.pack(side=TOP, pady=10)
b2 = Button(frame1, text='pusch2', command = But_Cmd('106'))
b2.config(background= 'light blue')
b2.pack(side=TOP, pady=10)
mainloop()

上面的 python 正在使用按钮命令传递代码。代码使用字典开关转到函数调用。我以同样的方式使用"入口"小部件,没有问题。表单和按钮显示没有问题;按钮命令将不起作用。我还在 GUI 底部得到"太多连接"。我正在使用Wing IDE。

你在这里使用字符串:

command = But_Cmd('106')

但是您的实际字典是使用整数定义的:

Button_select = {
    100: Proc_button_100,  # etc.

所以很明显,这些函数永远不会被找到,因为你使用的键不在字典中。 (同样,你的按钮代码是106,但没有这样的功能。

我的建议是不要使用字典。完全。使用函数来获取所需的函数绝对没有任何好处,而不是首先使用所需的函数。

此外,为对象指定有意义的名称,而不是模糊的数字代码。

最新更新