【问题标题】:Python - Making a button change position randomlyPython - 使按钮随机更改位置
【发布时间】:2019-03-01 10:31:06
【问题描述】:

当我点击它时,我需要能够改变按钮的位置。每次我点击它时,位置都会随机变化。但我得到的只是一个错误。这是我的代码:

from tkinter import *
from random import randrange

class Window(Frame):

    def position(self):
        return randrange(0,400),randrange(0,300)

    def __init__(self,master=None):
        Frame.__init__(self,master)
        self.master = master
        self.__init__window()

    def __init__window(self):
        self.master.title("GUI")
        self.pack(fill=BOTH, expand=1)
        Button1 = Button(self, text="Click me if you can",command=self.Message)
        Button1.place(*position())
        menu=Menu(self.master)
        self.master.config(menu=menu)
        file = Menu(menu)
        file.add_command(label="Exit", command=self.client_exit)
        menu.add_cascade(label="File",menu=file)
        edit = Menu(menu)
        edit.add_command(label="Show text", command=self.showText)
        menu.add_cascade(label="Edit", menu=edit)

    def Message(self):
        print("Hello world")

    def showText(self):
        text = Label(self, text="Hey there!")
        text.pack()

    def client_exit(self):
        exit()

root = Tk()
root.geometry("400x300")
app = Window(root)
root.mainloop()

“Button1.place”是需要更改的按钮的位置,但我完全不知道该怎么做。我也使用了变量。

【问题讨论】:

  • 你得到什么错误?请修改问题以包含输出

标签: python user-interface button tkinter


【解决方案1】:

似乎place() 想要关键字参数。你可以让函数position()返回一个dict并在place()语句中解压:

def position(self):
    return {'x':randrange(0,400),'y':randrange(0,300)}

将按钮放置在:

self.Button1.place(**self.position())

您还需要在按钮名称前加上“self”前缀,以便能够从函数 __init__window() 之外访问它。

然后只需在按钮回调函数中添加place() 语句的副本:

def Message(self):
    print("Hello world")
    self.Button1.place(**self.position())

至少对我来说这很好用(win10 下的 Python 3.6.5)。

您必须减少为 x 和 y 生成的随机值,否则按钮的某些部分会偶尔出现在窗口之外...

【讨论】:

  • 我现在似乎仍然遇到问题,它在 ** 必须是映射之后给我一个 place_configure() 参数错误,而不是按钮行所在的方法。我已经做出了改变,但并没有真正改变。
  • 我想你忘记了position() 函数中的括号:self.Button1.place(**self.position())
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多