【问题标题】:Configure not recognized [duplicate]配置无法识别[重复]
【发布时间】:2022-01-13 04:44:52
【问题描述】:

我正在尝试制作数字生成器,但遇到了问题。它不识别配置。我对 tkinter 有点陌生,并且凭借我对 python 的初学者知识,它真的让我头疼。这是代码:

from tkinter import messagebox
import random
from tkinter import *
from tkinter import ttk

window = Tk()
window.title("Random Number Generator")
window.geometry('350x200')

title_lbl = Label(window, text="Press the button to generate!").grid(row=0, column=1)

def rannum():
    ran = random.randint(0, 10000000)
    com = ans_lbl.configure(text=ran)
    
    
btn = Button(window, text='Randomize', command=rannum).grid(row=1, column=0)

ans_lbl = Label(window, text='').grid(row=2, column=0)

window.mainloop()

这是我收到的错误:

File "C:\Users\(redacted)\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
    return self.func(*args)
  File "c:\Users\(redacted)\Documents\(redacted)\(redacted)", line 15, in rannum
    com = ans_lbl.configure(text=ran)
AttributeError: 'NoneType' object has no attribute 'configure'

【问题讨论】:

标签: python tkinter


【解决方案1】:

ans_lbl 被分配了值None,因为当你初始化它时,你将它设置为 Label.grid() 的值。您要做的是将 Label() 和 .grid() 调用分开。

替换

ans_lbl = Label(...).grid(...)

有了这个:

ans_lbl = Label(...)

ans_lbl.grid(...)

为了便于阅读,我在下面完成了这项工作,并将 ans_lbl 的初始化移到 title_lbl 旁边。

import random
from tkinter import *
from tkinter import ttk

window = Tk()
window.title("Random Number Generator")
window.geometry('350x200')

title_lbl = Label(window, text="Press the button to generate!").grid(row=0, column=1)
ans_lbl = Label(window, text='')
ans_lbl.grid(row=2, column=0)

def rannum():
    ran = random.randint(0, 10000000)
    com = ans_lbl.configure(text=ran)


btn = Button(window, text='Randomize', command=rannum).grid(row=1, column=0)


window.mainloop()

【讨论】:

    【解决方案2】:

    你能不能把你的方法改成这个,再试一次。

    def rannum():
        ran = random.randint(0, 10000000)
        # com = ans_lbl.configure(text=ran)
        ans_lbl = Label(window, text=ran).grid(row=2, column=0)
    

    【讨论】:

    • 您每次都在创建新标签,而不是更改现有标签
    猜你喜欢
    • 1970-01-01
    • 2018-07-21
    • 2021-02-20
    • 2021-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-31
    • 2011-04-27
    相关资源
    最近更新 更多