一旦使用tkinter初始化我如何更新我的gui?

问题描述 投票:-1回答:2

为什么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()
python python-3.x user-interface tkinter
2个回答
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
投票

你有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()
© www.soinside.com 2019 - 2024. All rights reserved.