name' set_hour'没有定义

时间:2015-11-12 02:39:57

标签: python python-3.x tkinter

我正在使用tkinter处理这个python代码。我想将标签set_hour的状态更改为" active"按下' j。每次我运行我的代码时,我都会收到错误消息,说明没有定义set_hour。我是否需要使用" self"这里?为什么你能解释一下。谢谢

class SetClock:
def __init__(self, parent):
    self.myParent = parent

    self.current_datetime_label = tkinter.Label(root, text=datetime.datetime.now(), bg = "black", foreground="white").grid(row=1)
    #current_time_label.pack()

    self.menu_label = tkinter.Label(root, text="Menu", bg="sky blue", foreground="black",width=18).grid(row=2)
    self.set_day = tkinter.Label(root, text="Set Day", bg="blue",foreground="white",width=9,state="active").grid(row=2, column=1)
    self.set_hour = tkinter.Label(root, text="Set Hour",bg="blue",foreground="white",width=9).grid(row=2, column=2)
    self.set_mintutes = tkinter.Label(root, text="Set Minutes", bg="blue",foreground="white",width=10).grid(row=2, column=3)
    self.exit_label = tkinter.Label(root, text="Exit", bg="black", foreground="white").grid(row=2, column=4)

    self.day_menu_label = tkinter.Label(root, text="Day",bg="sky blue",width=18).grid(row=3)
    #menu_label.pack(side="right")
    #current_time_label.pack()

def navigate_menu(event):
    current_pressed = str(event.char)
    print("pressed", current_pressed)
    if current_pressed is 'j':
        print("ok")
        set_hour.config(state="active")

root = Tk()    
#frame = Frame(root)
setclock = SetClock(root)
root.title("Set Clock")
root.minsize(width=500,height=500)
root.bind("<Key>",SetClock.navigate_menu)
root.mainloop()

2 个答案:

答案 0 :(得分:2)

您需要将navigate_menu定义为实例方法:

def navigate_menu(self, event):
    current_pressed = str(event.char)
    print("pressed", current_pressed)
    if current_pressed is 'j':
        print("ok")
        self.set_hour.config(state="active")

绑定它时,改为传递绑定方法:

root.bind("<Key>", setclock.navigate_menu)

另外,单独Label创建行和grid()行。否则,self.set_hour变为None,因为grid()方法返回None

self.set_hour = tkinter.Label(root, text="Set Hour",bg="blue",foreground="white",width=9)
self.set_hour.grid(row=2, column=2)

答案 1 :(得分:0)

grid()返回None,因此您必须

self.set_hour = tkinter.Label(...)
self.set_hour.grid(...)