如何重新定位按钮?

时间:2017-03-09 07:42:18

标签: python python-3.x tkinter

如何修复程序的这一部分,将按钮重新定位到屏幕上的新位置?

movingbutton1 = Button(root, text = 'Click Me' ... ).place(relx = .5, rely = .5)
time.sleep(3)
movingbutton1(root, text = 'Click Me' ... ).place(relx = .3, rely = .3)

3 个答案:

答案 0 :(得分:1)

要移动已放置的窗口小部件,您可以使用place_configure(relx=new_x, rely=new_y)

要在用户点击按钮时移动按钮,请传递一个将此按钮移动到按钮的command选项的功能。

import tkinter as tk
import random

def move():
    x = random.random()
    y = random.random()
    moving_button.place_configure(relx=x, rely=y)

root = tk.Tk()

moving_button = tk.Button(root, text='Click Me', command=move)

moving_button.place(relx=0.5, rely=0.5, anchor='center')

root.mainloop()

答案 1 :(得分:0)

您可以使用.after方法在一定时间后移动窗口小部件,如下所示:

import tkinter as tk
import time

class App(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.button1 = tk.Button(parent, text = 'Click Me')
        self.button1.place(relx = .5, rely = .5)
        self.button1.after(3000, self._moveButton) # Call method after 3 secs

    def _moveButton(self):
        # reposition button 
        self.button1 .place(relx = .3, rely = .3)

if __name__ == "__main__":
    window = tk.Tk()
    window.geometry('500x200')
    app = App(window)
    window.mainloop()

答案 2 :(得分:0)

以下答案是你想要的

movingbutton1 = Button(root, text = 'Click Me' ... )
movingbutton1.place(relx = .5, rely = .5)
time.sleep(3)
movingbutton1.place(relx = .3, rely = .3)