更改Tkinter窗口中标签的位置
问题描述:
我正在写一个简单的程序,用于拉出图像(BackgroundFinal.png)并将其显示在窗口中。我希望能够按下窗口上的按钮将图片向下移动22个像素。除按钮之外的所有东西都不起作用。更改Tkinter窗口中标签的位置
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()
如果我没有记错的话,按钮应该改变全局的“B”值,因此改变标签的y位置。我非常感谢任何帮助,对于我可怕的公约感到遗憾。提前致谢!
答
感谢您的答复,但它是不是真的是我一直在寻找。我会发布我发现最适合其他人的问题。
实质上,在这种情况下,使用Canvas而不是标签要好得多。随着画布,你可以用canvas.move移动对象,这里是一个简单的示例程序
# Python 2
from Tkinter import *
# For Python 3 use:
#from tkinter import *
root = Tk()
root.geometry('500x500+100+100')
image1 = PhotoImage(file = 'Image.gif')
canvas = Canvas(root, width = 500, height = 400, bg = 'white')
canvas.pack()
imageFinal = canvas.create_image(300, 300, image = image1)
def move():
canvas.move(imageFinal, 0, 22)
canvas.update()
button = Button(text = 'move', height = 3, width = 10, command = move)
button.pack(side = 'bottom', padx = 5, pady = 5)
root.mainloop()
我的代码可能不是完美的(对不起!),但是这是基本的想法。希望我可以帮助其他人解决这个问题
答
这里有几个问题。
首先,您正在使用pack
和place
。一般来说,您只能在容器小部件中使用1个几何管理器。我不建议使用place
。这只是你需要管理的太多工作。
其次,当您构建按钮时,您将调用回调movedown
。这不是你想做的事 - 你要传递的功能,而不是函数的结果:
buttonup = Button(window, text = 'down', width = 5, command = movedown)
三,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()