我试图让按钮改变颜色让用户知道他们按下了按钮。我已经看到过这样的其他问题,但没有一个问题有帮助。我在编码方面很陌生,但一直在阅读有关tkinter及其所有模块的指导书。但我无法改变它的颜色
from tkinter import *
import os
import time
class Window(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master = master
self.init_window()
self.master.title("Conversion System")
def init_window(self):
self.pack(fill=BOTH, expand=1)
menu = Menu(self.master)
self.master.config(menu=menu)
file = Menu(menu)
file.add_command(label="Exit", command=self.client_close)
menu.add_cascade(label="File", menu=file)
conversionTab = Menu(menu)
menu.add_cascade(label="Conversions", menu=conversionTab)
conversionTab.add_checkbutton(label="Binary To Denary", command=self.binary2denary)
conversionTab.add_checkbutton(label="Hexadecimal to Denary", command=self.binary2denary)
conversionTab.add_command(label="System Info", command=self.SystemInfo)
# creating a button instance
userChoice = Label(text="Chose a converter!")
userChoice.pack(padx=0, pady=0, side=TOP)
b2dButton = Button(self, text="Binary to Denary", bg="white", fg="black", command=self.binary2denary)
b2dButton.pack(padx=10, pady=5, side=TOP)
hexaButton = Button(self, text="Hexadecimal to Denary", bg="white", fg="black", command=self.hexa2denary)
hexaButton.pack(padx=10, pady=5, side=TOP)
SystemInfo = Button(self, text="System Info", bg="white", fg="black", command=self.SystemInfo)
SystemInfo.pack(padx=10, pady=5, side=TOP)
quitButton = Button(self, text="Quit", bg="red", fg="black", command=self.client_close)
quitButton.pack(padx=5, pady=20, side=BOTTOM)
def SystemInfo(self):
os.startfile("Code")
def hexa2denary(self):
print("s")
def binary2denary(self):
print("s")
self.Button.configure(bg="Green")
错误代码:
Exception in Tkinter callback
s
Traceback (most recent call last):
File "C:\Python33\lib\tkinter\__init__.py", line 1442, in __call__
return self.func(*args)
File "C:/Users/Robert/Desktop/Robert's Python/Converter/Main.py", line 49, in binary2denary
self.Button.configure(bg="Green")
AttributeError: 'Window' object has no attribute 'Button'
答案 0 :(得分:0)
您没有self.Button
但b2dButton
要更改颜色
但您必须使用self.b2dButton
才能访问所有功能
在init_window()
内你需要
self.b2dButton = Button(...)
self.b2dButton.pack
内部方法binary2denary()
您需要
self.b2dButton.configure(bg="Green")
BTW:错误消息显示
File "C:/Users/Robert/Desktop/Robert's Python/Converter/Main.py", line 49, in binary2denary
self.Button.configure(bg="Green")
AttributeError: 'Window' object has no attribute 'Button'