2013-03-28 50 views
0

我正在寫一個簡單的程序,用於拉出圖像(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位置。我非常感謝任何幫助,對於我可怕的公約感到遺憾。提前致謝!

回答

2

感謝您的答覆,但它是不是真的是我一直在尋找。我會發布我發現最適合其他人的問題。

實質上,在這種情況下,使用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() 

我的代碼可能不是完美的(對不起!),但是這是基本的想法。希望我可以幫助其他人解決這個問題

4

這裏有幾個問題。

首先,您正在使用packplace。一般來說,您只能在容器小部件中使用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()