如何在 tkinter 中移动东西

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

我一整天都在尝试学习 tkinter 但无济于事。我发现的所有信息似乎都过时了,我见过一千种移动物体的方法,但它们都坚持一侧。我写 css 的时间比这还少。

from tkinter import *
from tkinter import ttk
root = Tk()
root.title('aaaa?')
root.geometry('400x300')
root.config(bg='#F2B33D')
frm = Frame(root, bg='#F2B33D')
frm.grid()
Label(frm, text="Hello World!").grid(column=0, row=0, ipadx=100)
Button(frm, text="Not yet").grid(column=0, row=3)
Button(frm, text="Quit", command=root.destroy).grid(column=2, row=3)

frm.pack(expand=True)
root.mainloop()

我想要处理这个失败的代码是将按钮对称地放置在下中心,将标签对称地放置在上中心,然后,知道用户是否单击了尚未按钮并将其存储在变量中。我什至还画了一幅很酷的图画。

image 谢谢

python tkinter grid
1个回答
0
投票

要在 tkinter 中实现所需的布局和功能,您可以使用包几何管理器对称定位小部件并处理按钮单击。这是修改后的代码:

from tkinter import *
from tkinter import ttk

def on_not_yet_click():
    global user_clicked
    user_clicked = True

root = Tk()
root.title('aaaa?')
root.geometry('400x300')
root.config(bg='#F2B33D')

frm = Frame(root, bg='#F2B33D')
frm.pack(expand=True)

Label(frm, text="Hello World!").pack(pady=50)

Button(frm, text="Not yet", command=on_not_yet_click).pack(side=LEFT, padx=20)
Button(frm, text="Quit", command=root.destroy).pack(side=RIGHT, padx=20)

# Set the initial value of user_clicked to False
user_clicked = False

root.mainloop()

在此修改后的代码中,我们使用 pack 方法对称放置标签和按钮。我们添加一些填充以在标签和按钮之间创建间距。将“尚未”按钮的 side 参数设置为 LEFT,将“退出”按钮设置为 RIGHT。

另外,我们定义了on_not_yet_click函数来处理“Not Yet”按钮的点击事件。单击按钮时,会将 user_clicked 变量设置为 True。

现在,如果用户单击“尚未”按钮,则 user_clicked 变量将为 True,您可以根据需要在代码中使用它。

© www.soinside.com 2019 - 2024. All rights reserved.