tk小白,在做毕设,卡在组件(notebook其中一个tab里面的组件)随窗口尺寸的变化而自动调整大小这个功能实现上
-
问题描述:在将窗口
bind('<Configure>', self.myCall)
后,造成:
(1)打开窗口就会频繁触发self.myCall
,执行里面的代码
(2)只想在窗口尺寸改变时执行self.myCall
中想执行的代码,但现在只要窗口位置改变时(啊,是'<Configure>'
这个家伙的锅),也将执行,导致不想要的结果 -
问题代码举例:
import tkinter as tk
class MyWindow(tk.Tk):
def __init__(self):
super(MyWindow, self).__init__()
self.title('我是无辜的窗口')
self.geometry('400x300')
# 绑定动作 <Configure>
self.bind('<Configure>', self.myCall)
# 定义触发的事件
def myCall(self, event=None):
print('调用 myCall 函数')
print('此时窗口尺寸为:{}x{}'.format(self.winfo_width(),self.winfo_height()))
if __name__ == '__main__':
myWindow = MyWindow()
myWindow.mainloop()
运行后,只要移动窗口就会:
或者添加一个 Label 后,一运行窗口就会:
import tkinter as tk
class MyWindow(tk.Tk):
def __init__(self):
super(MyWindow, self).__init__()
self.title('我是无辜的窗口')
self.geometry('400x300')
self.label = tk.Label(self, text='我是无辜的label')
self.label.pack()
# 绑定动作 <Configure>
self.bind('<Configure>', self.myCall)
# 定义触发的事件
def myCall(self, event=None):
print('调用 myCall 函数')
print('此时窗口尺寸为:{}x{}'.format(self.winfo_width(),self.winfo_height()))
if __name__ == '__main__':
myWindow = MyWindow()
myWindow.mainloop()
- 解决方法:添加适当的延时
import tkinter as tk
import time
class MyWindow(tk.Tk):
def __init__(self):
super(MyWindow, self).__init__()
# 最后一次调用 myCall 的时间
self.last_time = time.time()
self.title('我是无辜的窗口')
self.geometry('400x300')
self.label = tk.Label(self, text='我是无辜的label')
self.label.pack()
# 绑定动作 <Configure>
self.bind('<Configure>', self.myCall)
# 定义触发的事件
def myCall(self, event=None):
current_time = time.time()
if (current_time - self.last_time) > 0.5: # 延时0.5s
print('调用 myCall 函数')
print('此时窗口尺寸为:{}x{}'.format(self.winfo_width(),self.winfo_height()))
self.last_time = time.time()
if __name__ == '__main__':
myWindow = MyWindow()
myWindow.mainloop()