[英]Tkinter button color flashing for no reason
我正在制作一個刷新函數來更改tkinter中按鈕的顏色,問題是該顏色必須來自另一個返回字符串的函數,並且每次我更新所有內容時都會閃爍一下。
我嘗試使用StringVar()並僅更新顏色而不更新整個布局,但是它只會卡在循環中而從不顯示布局。 我還嘗試將所有對象都轉儲到列表中,然后立即更改整個網格,而不是一次又一次地更改網格,但沒有成功。
該代碼的核心是:
root = Tk()
frame=Frame(root)
root.title("States")
Grid.rowconfigure(root, 0, weight=1)
Grid.columnconfigure(root, 0, weight=1)
frame.grid(row=0, column=0, sticky=N+S+E+W)
grid=Frame(frame)
grid.grid(sticky=N+S+E+W, column=0, row=7, columnspan=2)
Grid.rowconfigure(frame, 7, weight=1)
Grid.columnconfigure(frame, 0, weight=1)
def loop_1():
for x in range(4):
for y in range(3):
btnxy(x,y,frame)
for x in range(4):
Grid.columnconfigure(frame, x, weight=1)
for y in range(3):
Grid.rowconfigure(frame, y, weight=1)
root.after(1000,loop_1)
loop_1()
btnxy創建一個按鈕並將其放置在網格中
def btnxy(x,y,frame):
index=4*y+x+1
if index>8:
message="Relay "+str(index-8)
btn = Button(frame,text=message, command=lambda p=(index-8): Relay(index-8), bg="blue", relief="groove", height=10, width=30)
else:
message="Entrée "+str(index)
color=check_color(index)
btn = Button(frame,text=message, command="", bg=color, relief="groove", height=10, width=30)
btn.grid(column=x, row=y, sticky=N+S+E+W
而check_color是一個返回“紅色”或“綠色”字符串的函數
據我了解,這應該不需要太多的處理能力,因此更新比較容易,但是會閃爍。
我試圖對您的代碼進行一些修改,但老實說,我無法使其正常工作,並且不了解其背后的邏輯。 有很多問題是不對的:
1)全球進口不好。 不要from tkinter import *
。 而是將import tkinter as tk
。 這樣可以提高可讀性,使事情更明確,並具有許多其他好處(您可以在Google上輕松找到更多信息)
2)您可以使用功能loop1
將按鈕放置在所需的幀中。 一切都很好,但是您不要將框架作為參數傳遞,對於root
也是一樣。 如果確實修改了代碼以解決此問題,您將看到閃爍消失,盡管由於缺少參數, root.after
也會遇到問題。
解決方案是更改應用程序的結構,以便可以輕松訪問和使用按鈕和根目錄。 入門的方法可以是以下代碼:
import tkinter as tk
from random import shuffle
def get_random_colors():
colors = ["red" for i in range(4)] + ["blue" for i in range(4)] + ["green" for i in range(4)]
shuffle(colors)
return colors
class MyGUI(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.frame = tk.Frame()
self.frame.pack()
self.n_rows = 3
self.n_cols = 4
self.bt_list = []
for x in range(self.n_rows):
for y in range(self.n_cols):
self.bt_list.append(tk.Button(self.frame, text="Button {}.{}".format(x, y)))
self.bt_list[-1].grid(row=x, column=y)
def change_colors(self):
colors = get_random_colors()
for index, button in enumerate(self.bt_list):
button.configure(bg=colors[index])
self.after(5000, self.change_colors)
root = MyGUI()
root.after(5000, root.change_colors)
root.mainloop()
首先,主框架現在是該類的一個屬性,因此只要將self傳遞給函數,只要我在類中需要它,只要調用self.frame
就足夠了。
然后,我決定將按鈕存儲在列表中,這樣我就可以始終通過self
在班級中訪問它們。 這很有用,因為在change_colors函數中,我可以循環瀏覽列表並通過.configure(bg=<color here>)
更改按鈕。
最后一點是.after
。 我在定義root
之后立即在類構造函數外部調用它,然后在使用self
的change_colors
函數內部調用它。 最終代碼應每5秒鍾隨機更改按鈕的顏色。
希望能幫助到你!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.