为什么screen.destroy()抛出一个异常,屏幕是一个空对象?我按下按钮时尝试更新我的屏幕标签,但它没有发生。
from tkinter import *
def buttonOne():
num1.append("1")
number = ""
count = 0
while count < len(num1):
number = number + str(num1[count])
count += 1
screen1 = Label(text=number).grid(column=0, row=0)
screen.destroy()
def main():
window = Tk()
window.title("Calculator")
global num1
num1 = []
global screen
screen = Label(text="0.0").grid(column=0, row=0)
button1 = Button(text="1", command=buttonOne)
button1.grid(column=0, row=2)
window.mainloop()
main()
你有问题,因为你这样做
screen = Label(text="0.0").grid(column=0, row=0)
并且它将None
交给screen
,因为grid()
/ pack()
/ place()
返回None
你必须分两行
screen = Label(text="0.0")
screen.grid(column=0, row=0)
顺便说一句:您可以使用方法之一替换标签中的文本
screen["text"] = "new text"
screen.config(text="new text")
看到
def buttonOne():
num1.append("1")
number = ""
for item in num1:
number += str(item)
screen["text"] = number
因为您只将字符串放在列表中,所以您可以缩短它
def button_one():
num1.append("1")
screen["text"] = ''.join(num1)
完整版本
import tkinter as tk
def button_one():
num1.append("1")
screen["text"] = ''.join(num1)
def main():
global num1
global screen
num1 = []
window = tk.Tk()
window.title("Calculator")
screen = tk.Label(text="0.0")
screen.grid(column=0, row=0)
tk.Button(text="1", command=button_one).grid(column=0, row=2)
window.mainloop()
main()
你有Nonetype
错误,你必须把你的网格放在不同的线上。
from tkinter import *
def buttonOne():
global screen
num1.append("1")
number = ""
count = 0
while count < len(num1):
number = number + str(num1[count])
count += 1
screen1 = Label(text=number).grid(column=0, row=0)
screen.destroy()
def main():
global screen
window = Tk()
window.title("Calculator")
global num1
num1 = []
screen = Label(text="0.0")
screen.grid(column=0, row=0)
button1 = Button(text="1", command=buttonOne)
button1.grid(column=0, row=2)
window.mainloop()
main()