Python Tkinter按钮

时间:2015-03-31 13:58:55

标签: python tkinter

我在我的代码中使用了多个按钮,它们彼此相互接触。 我希望他们并肩, 我已在此处查看:Setting the position on a button in Python?并尝试了该问题的解决方案,

但是,我使用.pack,我需要将其更改为网格? 这就是我所拥有的:

#import tKinter
import sys
from tkinter import *
def mhello():
    mlabel1 = Label(window,text = 'Hello we have to start / да започне').pack()
def mhello1():
    mlabel2 = Label(window,text = 'Hello we have to stop / да спре').pack()
def mhello2():
    mlabel3 = Label(window,text = 'Hello we have to add / да добавите').pack()    
#create new window
window = Tk()

#set window title
window.title("Изпитване програмата")
#set window size
window.geometry("700x200")

#menu start
def donothing():
   filewin = Toplevel(window)
   print("Welcome to my test program, XOXO Katherina") 
   mlabel5 = Label(window,text = 'Welcome to my test program, XOXO Katherina').pack()
def leave():
     sys.exit(0)

menubar = Menu(window)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Exit", command=window.destroy)
menubar.add_cascade(label="File", menu=filemenu)

helpmenu = Menu(menubar, tearoff=0)
helpmenu.add_command(label="About...", command=donothing)
menubar.add_cascade(label="Help", menu=helpmenu)

window.config(menu=menubar)
#menu ends 

#buttons here 
mlabel = Label(window,text = 'My label').pack()
mbutton = Button(window,text = 'Start',command = mhello, fg = 'black',bg = 'red', height = '3',width = '5',bd = '3').pack()
mbutton1 = Button(window,text = 'Stop',command = mhello1, fg = 'black',bg = 'red', height = '3',width = '5',bd = '3').pack()
mbutton2 = Button(window,text = 'Add',command = mhello2, fg = 'black',bg = 'red', height = '3',width = '5',bd = '3').pack()
#end buttons
#draw the window start application
window.mainloop()

也尝试将按钮更改为:

#buttons here 
mlabel = Label(window,text = 'My label').pack()
mbutton = Button(window,text = 'Start',command = mhello, fg = 'black',bg = 'red', height = '3',width = '5',bd = '3')
mbutton.grid(row=0, column=0)

mbutton1 = Button(window,text = 'Stop',command = mhello1, fg = 'black',bg = 'red', height = '3',width = '5',bd = '3')
mbutton1.grid(row=1, column=0)

mbutton2 = Button(window,text = 'Add',command = mhello2, fg = 'black',bg = 'red', height = '3',width = '5',bd = '3')
mbutton2.grid(row=2, column=0)
#end buttons 

1 个答案:

答案 0 :(得分:2)

使用 pack(side = LEFT) pack(side = RIGHT)使用pack并排放置东西。

一般情况下,如果你正在做这个项目以外的任何事情,那么学习使用grid()绝对是个好主意。它有点复杂,但为放置提供了更大的灵活性而无需太多工作。可以在this site.

找到关于如何使用它们以及它们之间的差异的良好参考

<强>更新

如果你仍然坚持使用pack(),那么让事情集中在同一条线上会有点棘手。没有直接的方法使它工作,最简单的解决方法是创建一些东西来填充侧面的空间,以便按钮被强制到中间。这样的事情可以解决问题:

spacing1 = Label(root, text=" "*50).pack(side=LEFT)
button1 = Button(...)
button1.pack(side=Left)
spacing2 = Label(root, text=" "*50).pack(side=RIGHT)
button2 = Button(...)
button2.pack(side=RIGHT)

请注意,您必须确定正确的空格数,以便通过反复试验使按钮显示为中心。