小智1998 发表于 2021-5-20 07:39:25

tkinter使用grid进行页面布局时报错

想请教一下,写了几个message的按钮,然后想给它们进行页面布局,实现按钮全部靠左对齐,报以下错误
tkinter.TclError: cannot use geometry manager grid inside . which already has slaves managed by pack
原代码如下:

import tkinter as tk
import tkinter.messagebox


window = tk.Tk()
window.title('my window')
window.geometry('300x200')



def hit_me():
    tk.messagebox.showinfo(title = 'Hi',message = 'hahaha')

def Warning():
    tk.messagebox.showwarning(title = 'warnig',message = 'please check your setting')

def Error():
    tk.messagebox.showerror(title = 'error',message = 'error 404')

def Ask():
    result = tk.messagebox.askyesno(title = 'asking',message = 'Ok to open?')
    if result == 1:
      print('saved successful!')
    else:
      print('fail to save!')
   
   

b1 = tk.Button(window,text = 'hit me',command = hit_me)
b1.pack()
b2 = tk.Button(window,text = 'warning',command = Warning)
b2.pack()
b3 = tk.Button(window,text = 'error',command = Error)
b3.pack()
b4 = tk.Button(window,text = 'asking',command = Ask)
b4.pack()

b1.grid(row = 0,column = 0)
b2.grid(row = 1,column = 0)
b3.grid(row = 2,column = 0)
b4.grid(row = 4,column = 0)

window.mainloop()

网上搜索说是place不能和grid一起用,但是我好像没用到place,请教一下大家这段代码的问题

qq1151985918 发表于 2021-5-20 07:53:00

你用了pack,这些都不能一起用

Twilight6 发表于 2021-5-20 12:59:27



楼主应该搜错或看错了,是 pack 与 grid 不能对同一个父组件使用,而 place 可以混用

你代码中先用了 pack() 进行布局管理,又用了 grid() 进行,肯定会导致报错呀

参考代码:

import tkinter as tk
import tkinter.messagebox

window = tk.Tk()
window.title('my window')
window.geometry('300x200')


def hit_me():
    tk.messagebox.showinfo(title='Hi', message='hahaha')

def Warning():
    tk.messagebox.showwarning(title='warnig', message='please check your setting')

def Error():
    tk.messagebox.showerror(title='error', message='error 404')

def Ask():
    result = tk.messagebox.askyesno(title='asking', message='Ok to open?')
    if result == 1:
      print('saved successful!')
    else:
      print('fail to save!')

b1 = tk.Button(window, text='hit me', command=hit_me)
b1.grid(row=0, column=0)
b2 = tk.Button(window, text='warning', command=Warning)
b2.grid(row=1, column=0)
b3 = tk.Button(window, text='error', command=Error)
b3.grid(row=2, column=0)
b4 = tk.Button(window, text='asking', command=Ask)
b4.grid(row=4, column=0)

window.mainloop()


小智1998 发表于 2021-5-21 06:37:35

qq1151985918 发表于 2021-5-20 07:53
你用了pack,这些都不能一起用

感谢回复,问题已解决

小智1998 发表于 2021-5-21 06:38:34

Twilight6 发表于 2021-5-20 12:59
楼主应该搜错或看错了,是 pack 与 grid 不能对同一个父组件使用,而 place 可以混用

你代码中先用 ...

是的,是报的pack错误,问题已解决,非常感谢!
页: [1]
查看完整版本: tkinter使用grid进行页面布局时报错