Tkinter更改按钮的坐标和大小

问题描述 投票:2回答:1

我想知道如何更改按钮的坐标和大小。我知道你可以做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()
python tkinter
1个回答
1
投票

Tkinter有三位布局经理

您可以将x,yplace()一起使用,但之后您不应该使用其他自动计算位置的管理器,当您使用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()
© www.soinside.com 2019 - 2024. All rights reserved.