我正在编写一个简单的程序,用于拉出图像 (BackgroundFinal.png) 并将其显示在窗口中。我希望能够按下窗口上的按钮将图片向下移动 22 像素。一切正常,除了按钮不做任何事情。
import Tkinter
import Image, ImageTk
from Tkinter import Button
a = 0 #sets inital global 'a' and 'b' values
b = 0
def movedown(): #changes global 'b' value (adding 22)
globals()[b] = 22
return
def window(): #creates a window
window = Tkinter.Tk();
window.geometry('704x528+100+100');
image = Image.open('BackgroundFinal.png'); #gets image (also changes image size)
image = image.resize((704, 528));
imageFinal = ImageTk.PhotoImage(image);
label = Tkinter.Label(window, image = imageFinal); #creates label for image on window
label.pack();
label.place(x = a, y = b); #sets location of label/image using variables 'a' and 'b'
buttonup = Button(window, text = 'down', width = 5, command = movedown()); #creates button which is runs movedown()
buttonup.pack(side='bottom', padx = 5, pady = 5);
window.mainloop();
window()
Run Code Online (Sandbox Code Playgroud)
如果我没记错的话,按钮应该更改全局“b”值,从而更改标签的 y 位置。我真的很感谢任何帮助,为我糟糕的约定感到抱歉。提前致谢!
你在这里有一些问题。
首先,您正在使用pack和place。通常,您应该只在容器小部件中使用 1 个几何管理器。我不建议使用place. 您需要管理的工作太多了。
其次,您在movedown构造按钮时调用回调。这不是你想要做的——你想传递函数,而不是函数的结果:
buttonup = Button(window, text = 'down', width = 5, command = movedown)
Run Code Online (Sandbox Code Playgroud)
第三,globals返回当前命名空间的字典——其中不可能有整数键。要获得对被 引用的对象的引用b,您需要globals()["b"]. 即使这样做了,更改b全局命名空间中的值也不会更改标签的位置,因为标签无法知道该更改。一般来说,如果您需要使用globals,您可能需要重新考虑您的设计。
这是我将如何做的一个简单示例...
import Tkinter as tk
def window(root):
buf_frame = tk.Frame(root,height=0)
buf_frame.pack(side='top')
label = tk.Label(root,text="Hello World")
label.pack(side='top')
def movedown():
buf_frame.config(height=buf_frame['height']+22)
button = tk.Button(root,text='Push',command=movedown)
button.pack(side='top')
root = tk.Tk()
window(root)
root.mainloop()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
28602 次 |
| 最近记录: |