Python 更改标签在Tkinter窗口中的位置
我正在编写一个简单的程序,它可以调出一个image BackgroundFinal.png并将其显示在一个窗口中。我希望能够按下窗口上的按钮,将图片向下移动22像素。除了按钮不起任何作用外,其他一切都正常Python 更改标签在Tkinter窗口中的位置,python,tkinter,Python,Tkinter,我正在编写一个简单的程序,它可以调出一个image 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():
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位置。我真的很感激任何帮助,为我糟糕的习惯感到抱歉。提前谢谢 这里有一些问题 首先,您使用的是打包和放置。通常,在容器小部件中只应使用1个几何体管理器。我不建议使用这个地方。你需要管理的工作太多了 其次,在构造按钮时调用回调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()
谢谢你的回复,但这并不是我想要的。我会在这里发布我发现对其他有同样问题的人最有效的方法 本质上,在这种情况下,使用画布而不是标签要好得多。使用画布,您可以使用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()
我的代码可能不完美抱歉!但这是最基本的想法。希望我能帮助其他人解决这个问题这个答案并没有告诉我如何移动标签。。。