[Python] tkinter AttributeError: ‘NoneType’ object has no attribute ‘configure’

遇到應該是 global variable, 但是放在 tkinter 裡的 command 去存取時,被存取的 variable 是空的None.

會 Error 的 code:

!/usr/bin/env python
encoding=utf-8
from tkinter import *
window = None
lbl = None
btn = None
def btn_clicked():
lbl.configure(root, text="Button was clicked !!")
def MainMenu(root):
lbl = Label(root, text="Hello World", font=("Arial Bold", 50))
lbl.grid(column=0, row=0)
btn = Button(root, text="Click Me", command=btn_clicked)btn.grid(column=1, row=0)
def main():
root = Tk()
root.title("Welcome to Max app")
GUI = MainMenu(root)
root.geometry('450x400')
root.mainloop()
if name == "main":
main()

error message:

AttributeError: 'NoneType' object has no attribute 'configure'

解法:幫變數們加 global 即可。範例:
https://github.com/MorvanZhou/tutorials/blob/master/tkinterTUT/tk2_label_button.py

import tkinter as tk
window = tk.Tk()
window.title('my window')
window.geometry('200x100')
var = tk.StringVar()
l = tk.Label(window, textvariable=var, bg='green', font=('Arial', 12), width=15,
height=2)
l = tk.Label(window, text='OMG! this is TK!', bg='green', font=('Arial', 12), width=15, height=2)
l.pack()
on_hit = False
def hit_me():
global on_hit
if on_hit == False:
on_hit = True
var.set('you hit me')
else:
on_hit = False
var.set('')
b = tk.Button(window, text='hit me', width=15,
height=2, command=hit_me)
b.pack()
window.mainloop()

相關文章

寫留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *