社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

python-随意改变按钮的位置

Kiyo • 6 年前 • 1535 次点击  

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

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社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/30670
 
1535 次点击  
文章 [ 1 ]  |  最新文章 6 年前
figbeam
Reply   •   1 楼
figbeam    6 年前

似乎 place() 需要关键字参数。你可以让功能 position() 返回一个dict并将其解压缩到 位置() 声明:

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

将按钮放置在:

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

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

然后简单地添加 位置() 按钮回调函数中的语句:

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

至少对我来说这是正常的(Win10下的python 3.6.5)。

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