Skip to main content
 首页 » 编程设计

python之Tkinter 改变按钮的坐标和大小

2025年01月19日11birdshome

我想知道如何更改按钮的坐标和大小。我知道您可以执行 button1.pack(side=RIGHT) 但如果我想说 button1.pack(x=100, y=40) 怎么办?我试过 button1.geometry 但没用。

回答: 我执行了 button1.place(x=0, y=0) 按钮转到了顶角。 如果有人好奇,这是我使用的代码:

from tkinter import * 
 
t = Tk() 
 
t.title("Testing") 
 
t.geometry("250x250") 
 
MyButton = Button(t, text="Click Me") 
 
MyButton.pack() 
 
def Clicked(event): 
 
    MyButton.place(x=0, y=0) 
 
MyButton.bind("<Button-1>" ,Clicked) 
 
MyButton.pack() 
 
t.mainloop() 

请您参考如下方法:

Tkinter 具有三个布局管理器

您可以将 x,y 与 place() 一起使用,但是您不应该使用其他自动计算位置的管理器,当您放置一些东西时它们可能会出现问题手动使用 pack()。

但是你可以放置Frame(使用place())并在Frame中使用其他管理器

pack() 和 grid() 更受欢迎,因为它们会在您更改大小或在不同系统上使用时自动计算位置。


几天前为其他问题创建的示例。

Button 将 Frame 移动到随机位置。

编辑:现在 Button 将自身移动到随机位置并改变高度。

import tkinter as tk 
import random 
 
# --- function --- 
 
def move(): 
    #b.place_forget() # it seems I don't have to use it  
                      # to hide/remove before I put in new place 
    new_x = random.randint(0, 100) 
    new_y = random.randint(0, 150) 
    b.place(x=new_x, y=new_y) 
 
    b['height'] = random.randint(1, 10) 
 
# --- main --- 
 
root = tk.Tk() 
 
b = tk.Button(root, text='Move it', command=move) 
b.place(x=0, y=0) 
 
root.mainloop()