为什么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()
答案 0 :(得分:0)
你有问题因为你做了
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()
答案 1 :(得分:-1)
如果您遇到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()