我的目标是最终有一些标签和条目出现并与一周中的不同日期相对应。我目前正在努力获取按钮绑定以生成不同的标签,具体取决于选择的星期几。它有点工作,但不是我的期望,而不是我真正想要的。现在我必须点击两次按钮才能更新标签。我对编程还很陌生,我感谢您提供的任何帮助!
root = Tk()
root.geometry('300x300')
root.title('Day')
frame3 = Frame(root)
frame4 = Frame(root)
frame3.grid()
dayFrame = Frame(frame4)
class App(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.var1 = StringVar()
self.var1.set('')
self.sunBtn = Button(frame3, text='Sunday', command=lambda day='Sunday': self.var1.set(day))
self.sunBtn.bind('<Button-1>', self.openFrame)
self.sunBtn.grid(row=1, column=0)
self.monBtn = Button(frame3, text='Monday', command=lambda day='Monday': self.var1.set(day))
self.monBtn.bind('<Button-1>', self.openFrame)
self.monBtn.grid(row=1, column=1)
def openFrame(self,*args):
frame4.grid()
dayFrame.grid()
dayLbl = Label(dayFrame, text=self.var1.get())
dayLbl.grid(row=1, column=0)
app = App(root)
app.mainloop()
更新:我意识到自己的错误。我感到愚蠢。我换了
self.var1.set('')
与
self.var1.trace('w', self.openFrame)
似乎一切正常。希望这可以帮助另一个初学者!
答案 0 :(得分:0)
不要同时使用bind和command: (不要忘记写下你的输入行)
from tkinter import *
root = Tk()
root.geometry('300x300')
root.title('Day')
frame3 = Frame(root)
frame4 = Frame(root)
frame3.grid()
dayFrame = Frame(frame4)
class App(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.var1 = StringVar()
self.var1.set('')
self.sunBtn = Button(frame3, text='Sunday', command= lambda: self.openFrame('Sunday'))
self.sunBtn.grid(row=1, column=0)
self.monBtn = Button(frame3, text='Monday', command=lambda: self.openFrame('Monday'))
self.monBtn.grid(row=1, column=1)
def openFrame(self, day):
frame4.grid()
dayFrame.grid()
dayLbl = Label(dayFrame, text=day)
dayLbl.grid(row=1, column=0)
app = App(root)
app.mainloop()
一个非常不同(可能更好)的解决方案:
from tkinter import *
import calendar
root = Tk()
root.geometry('600x300')
root.title('Day')
frame3 = Frame(root)
frame4 = Frame(root)
frame3.grid()
dayFrame = Frame(frame4)
class App(Frame):
def __init__(self, master):
Frame.__init__(self, master)
frame4.grid()
dayFrame.grid()
self.dayLbl = Label(dayFrame, text="")
self.dayLbl.grid(row=1, column=0)
for i, day in enumerate(calendar.day_name):
button = Button(frame3, text=day, command= lambda day=day:\
self.dayLbl.configure(text=day))
button.grid(row=1, column=i)
app = App(root)
app.mainloop()