【问题标题】:Tkinter change coordinates and size of a buttonTkinter 更改按钮的坐标和大小
【发布时间】:2017-12-16 03:08:35
【问题描述】:

我想知道如何更改按钮的坐标和大小。我知道您可以使用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()

【问题讨论】:

  • 您只能将 x,y 与布局管理器 place() 一起使用,但您不应该使用其他布局管理器 - pack()grid()

标签: python tkinter


【解决方案1】:

Tkinter 有三个布局管理器

您可以将x,yplace() 一起使用,但是您不应该使用其他自动计算职位的经理,当您使用pack() 手动输入某些内容时,他们可能会遇到问题。

但你可以把Frame(使用place())并在Frame中使用其他经理

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


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

ButtonFrame 移动到随机位置。

编辑:现在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()

【讨论】:

  • 如果我想让它在程序启动时转到随机坐标怎么办?
  • 在开始时使用随机值代替x=0, y=0,或者在b.place(x=0, y=0)之后运行move()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-07
  • 2018-09-27
  • 2021-01-29
  • 1970-01-01
  • 2011-03-19
  • 1970-01-01
  • 2016-06-17
相关资源
最近更新 更多