这是我试图编写的一个简单的测试脚本,它将帮助我自学Tkinter ......
from tkinter import *
def hello():
print("U pressed it lol")
global window1, window2
window2 = None
window1 = None
def setWindow(windowEnter):
global window
window = windowEnter
window = Tk()
window.attributes("-fullscreen", True)
def newScreen(newScreen, screenToDelete):
setWindow(newScreen)
print("New Window Created")
screenToDelete.destroy()
print("He ded lol")
setWindow(window1)
def setStuff():
button = Button(window1, text="hey", command=hello)
label = Label(window1, text="YoYoYo My dude")
button2 = Button(window1, text="Next Page", command = lambda: newScreen(window2, window1))
button.pack()
label.pack()
button2.pack()
setStuff()
当我运行此代码时,它会返回错误吗?
File "C:\Users\026341\Desktop\test.py", line 19, in newScreen
screenToDelete.destroy()
AttributeError: 'NoneType' object has no attribute 'destroy'
为什么这不起作用&我该如何解决?
提前致谢:) (顺便说一句,我正在使用python 3.6)
答案 0 :(得分:2)
你设置
[{}]
作为全局变量,然后将window2 = None
window1 = None
的命令函数定义为
button2
哪个调用lambda: newScreen(window2, window1)
,其值为window2,window1为newScreen
,因此出错。这里的根本问题是您的None
函数:
setWindow
它不会像你使用它一样工作。当您致电def setWindow(windowEnter):
global window
window = windowEnter
window = Tk()
window.attributes("-fullscreen", True)
时,您传递setWindow(window1)
的值,无法在全局范围内看到函数对该变量执行的操作。一个简单的例子是:
window1
将打印两次。
为了达到你想要的效果,我建议你使用字典来跟踪你的窗户。
def increment(a):
a +=1
x = 1
print(x)
increment(x)
print(x)
请注意:以前您的函数是from tkinter import *
def hello():
print("U pressed it lol")
global window1, window2
windows = {}
def setWindow(window_name):
windows[window_name] = Tk()
windows[window_name].attributes("-fullscreen", True)
def newScreen(newScreen_name, screenToDelete_name):
setWindow(newScreen_name)
print("New Window Created")
windows[screenToDelete_name].destroy()
del windows[screenToDelete_name] #delete invalid entry from dict
print("He ded lol")
setWindow("window1")
def setStuff():
button = Button(windows["window1"], text="hey", command=hello)
label = Label(windows["window1"], text="YoYoYo My dude")
button2 = Button(windows["window1"], text="Next Page", command = lambda: newScreen("window2", "window1"))
button.pack()
label.pack()
button2.pack()
setStuff()
,这是非常混乱/错误的样式,因为函数及其第一个参数共享相同的名称。无论如何我改变了它以突出显示它现在需要字符串作为参数,但请记住这一点。
答案 1 :(得分:-1)
我现在无法测试,但我发现了一个错误来源:
lambda: newScreen(window2, window1)
这会创建一个不带任何参数的lambda函数,因此window2和window1将为None,而None没有destroy()方法,因此错误。而是尝试:
lambda window2, window1: newScreen(window2, window1)