[英]Changing Button Color in a python GUI
import sys
from tkinter import *
def run_GUI():
# create the window
root = Tk()
frame = Frame(root)
frame.pack()
#modify root window
root.title("Simple GUI")
root.geometry("700x300") # w x h
def SP2T(): # Edit occurs here where I forgot to pit that the button was created in a called funtction
#Creates Row
frameSP2T = Frame(root)
frameSP2T.pack(side = TOP)
#Creating Buttons First Row
button1 = Button(frameSP2T, padx=13, pady = 6, bd=4, text="SW02",fg = "black", command = SW02)
button1.pack(side = LEFT)
def SW02():
print("SW02 is on")
button1["fg"] = "green"
#Sets up initial boot screen
#Creates Row
topframe = Frame(root)
topframe.pack(side = TOP)
#Creating Buttons First Row
buttonA = Button(topframe, padx=13, pady = 6, bd=4, text="SP2T",fg = "black", command = SP2T)
buttonA.pack(side = LEFT)
buttonB = Button(topframe, padx=12, pady = 6, bd=4, text="SP4T",fg = "black")
buttonB.pack(side = LEFT)
buttonC = Button(topframe, padx=12, pady = 6, bd=4, text="SP12T",fg = "black")
buttonC.pack(side = LEFT)
buttonD = Button(topframe, padx=12, pady = 6, bd=4, text="QUIT", fg="red",command=frame.quit)
buttonD.pack(side = LEFT)
#Kick off event loop
root.mainloop()
return
run_GUI()
我得到了錯誤:
Traceback (most recent call last):
File "C:\Python34\lib\tkinter\__init__.py", line 1487, in __call__
return self.func(*args)
File "C:\Python34\gui_attempt.py", line 25, in SW02
button1["fg"] = "green"
NameError: name 'button1' is not defined
更新版本有望顯示整個圖片
該程序還有更多內容,所以才說第60行,但這是問題所在。 我試圖更改按下按鈕時的顏色。
最簡單的解決方法是在需要訪問該對象的兩個函數的開頭添加global button
:
def SP2T():
global button1
...
def SW02():
global button1
...
但是,使用global
通常不是一個好兆頭-相反,您可以采用基於類的方法,如以下簡單示例所示:
import tkinter as tk
class MyGui(tk.Tk):
def __init__(self):
super(MyGui, self).__init__()
self.create_widgets()
def create_widgets(self):
self.frame = tk.Frame(self)
self.frame.pack()
self.buttonA = tk.Button(self.frame, padx=13, pady=6, bd=4, text="SP2T",
fg="black", command=self.SP2T)
self.buttonA.pack(side=tk.LEFT)
def SW02(self):
print("SW02 is on")
self.button1["fg"] = "green"
def SP2T(self):
self.button1 = tk.Button(self.frame, padx=13, pady=6, bd=4, text="SW02",
fg="black", command=self.SW02)
self.button1.pack(side=tk.LEFT)
if __name__ == "__main__":
root = MyGui()
root.mainloop()
您正在處理范圍問題。 在函數SW02()
發生異常,因為您試圖修改不在函數范圍內的對象。 您需要傳遞它。將SW02()
更改為以下內容:
def SW02(button1):
print("SW02 is on")
button1["fg"] = "green"
由於您將函數用作命令的動作,因此有一些選項可以將其實際傳遞。
使用lambda:
button1 = Button(frameSP2T, padx=13, pady = 6, bd=4, text="SW02",fg = "black", command = lambda: SW02(button1))
使用functools.partial:
from functools import partial
# other stuff
_SW02 = partial(SW02, button1)
button = Button(frameSP2T, padx=13, pady = 6, bd=4, text="SW02",fg="black", command=_SW02)
另外,按照jonrsharpe的回答中的建議,您可以將整個GUI函數重構為一個類,並使所有小部件成為類成員,然后將您的小部件操作與類方法而不是普通函數相關聯。 這樣,您修改GUI組件的所有功能都可以訪問它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.