在Mac和Windows不同的系統下有些坑
1. filedailog,colorchooser
如下代碼在Mac下報錯:NameError: name 'filedialog' is not defined
#在Windows下,
from tkinter import *
root = Tk()
def callback():
fileName = filedialog.askopenfilename()
print(fileName)
Button(root,text="openFile",command=callback).pack()
root.mainloop()
增加引用 tkinter.filedialog才能運行
#在Mac下
from tkinter import *
import tkinter.filedialog
root = Tk()
def callback():
fileName = tkinter.filedialog.askopenfilename()
print(fileName)
Button(root,text="openFile",command=callback).pack()
root.mainloop()
2.menu(在Mac下需要兩層才能達到效果)
#Windows
from tkinter import *
root = Tk()
def callback():
print('hello')
mb = Menubutton(root,text="click me", relief=RAISED)
mb.pack()
filemenu = Menu(mb,tearoff=False)
filemenu.add_command(label="Open", command=callback)
filemenu.add_command(label="Save", command=callback)
filemenu.add_separator()
filemenu.add_command(label="Quit", command=root.quit)
mb.config(menu=filemenu)
mainloop()
#Mac
import tkinter as tk
from tkinter import messagebox
root = tk.Tk()
root.title('aa')
root.geometry('500x200')
def hello():
messagebox.showinfo("information", "Information")
# it cannot open menu
menubar1 = tk.Menu(root)
menubar = tk.Menu(menubar1, tearoff=0)
menubar1.add_cascade(label='File', menu=menubar)
menubar.add_command(label="Hello",command=hello)
menubar.add_command(label="Quit",command=root.quit)
root.config(menu=menubar1)
root.mainloop()
本文介绍了在使用Python3的Tkinter库时遇到的问题,特别是在Mac和Windows系统下。包括filedialog和colorchooser模块在Mac下需要额外引用tkinter.filedialog才能正常运行,以及Mac系统中实现menu功能需要两层嵌套等常见坑。
1万+





