我正在制作一个基本的温度转换器,我有它所以你可以将celcius转换为farenheight,现在我试图制作它,以便你可以切换。我有这段代码:
from tkinter import *
bool1 = True
class App:
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.x = Label(frame, text = 'Celcius:').grid(row = 0, column = 0)
self.c_var = DoubleVar()
Entry(frame, textvariable = self.c_var).grid(row = 0, column = 1)
self.z = Label(frame, text = 'Farenheight:').grid(row = 1, column = 0)
self.result_var = DoubleVar()
Label(frame, textvariable = self.result_var).grid(row = 1, column = 1)
b1 = Button(frame, text = 'Switch', command = self.switch)
b1.grid(row = 2, columnspan = 2)
button = Button(frame, text = 'Convert', command = self.convert)
button.grid(row = 3, columnspan = 2)
return None
def convert(self):
c = self.c_var.get()
c = c * (9/5) + 32
self.result_var.set(c)
def switch(self):
global bool1
if bool1 == True:
bool1 = False
self.x.config(text = 'Farenheight:')
else:
bool1 = True
self.z['text'] = 'Celcius:'
root = Tk()
root.wm_title('Temp Converter')
app = App(root)
root.mainloop()
我收到的错误消息是:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\keith\AppData\Local\Programs\Python\Python35- 32\lib\tkinter\__init__.py", line 1550, in __call__
return self.func(*args)
File "C:\Users\keith\Desktop\tkinter.py", line 26, in switch
self.x.config(text = 'Farenheight:')
AttributeError: 'NoneType' object has no attribute 'config'
答案 0 :(得分:0)
问题来自于您将x和z属性(self.x,self.z)分配给tkinter标签但不分配给Tkinter.Label.grid()函数返回的事实,即无。
相反,将标签的声明及其网格配置分成两行,首先声明变量,然后在它们上调用网格函数,从而为标签本身分配x和z。
from tkinter import *
bool1 = True
class App:
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.x = Label(frame, text = 'Celcius:')
self.x.grid(row = 0, column = 0)
self.c_var = DoubleVar()
Entry(frame, textvariable = self.c_var).grid(row = 0, column = 1)
self.z = Label(frame, text = 'Farenheight:')
self.z.grid(row = 1, column = 0)
self.result_var = DoubleVar()
Label(frame, textvariable = self.result_var).grid(row = 1, column = 1)
b1 = Button(frame, text = 'Switch', command = self.switch)
b1.grid(row = 2, columnspan = 2)
button = Button(frame, text = 'Convert', command = self.convert)
button.grid(row = 3, columnspan = 2)
return None
def convert(self):
c = self.c_var.get()
c = c * (9/5) + 32
self.result_var.set(c)
def switch(self):
global bool1
if bool1 == True:
bool1 = False
self.x.config(text = 'Farenheight:')
else:
bool1 = True
self.z['text'] = 'Celcius:'
root = Tk()
root.wm_title('Temp Converter')
app = App(root)
root.mainloop()