原因是对应版本的python-tk没有安装, 安装对应的 python-tk 即可成功导入和使用. 如你安装的python版本为3.11, 就需要执行 brew install python-tk@3.11 安装3.11版本的tk
macos下的安装方法为
brew install python-tk
注意需要和你安装的python版本对应, 可以先使用 brew search python-tk 来搜索可用的python-tk包的版本.
brew search python-tk
==> Formulae
python-tk@3.10 python-tk@3.9 python@3.7 python@3.9
python-tk@3.11 python-yq python@3.8
如果你安装的python版本为3.11 就需要安装 python-tk@3.11 , 如果版本不对应你在使用venv环境时是找不到 tk包的
brew install python-tk@3.11
没有安装python-tk 还会导致 msilib模块未找到无法使用 Listbox 的错误, 这个模块默认只存在于win32系统中可用
ModuleNotFoundError: No module named 'msilib'
完整示例代码
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from tkinter import *
root = Tk()
# height 默认显示10条数据 listBox = Listbox(root, height=11)
# 为了在某个组件上安装垂直滚动条,需要做两件事:
# 1.设置该组件的yscrollcommand选项为Scrollbar组件的set()方法
# 2.设置Scrollbar组件的command选项为该组件的yview()方法
sb = Scrollbar(root)
sb.pack(side=RIGHT, fill=Y)
listBox = Listbox(root, yscrollcommand=sb.set)
listBox.insert(0, TkVersion)
for i in range(100):
listBox.insert(END, i) # ListBox添加数据
listBox.pack()
listBox.see(20) # 调整列表框的位置,使得 index 参数指定的选项是可见的
sb.config(command=listBox.yview)
def delete():
listBox.delete(ACTIVE) # 删除选中的
delButton = Button(root, text="删除", command=delete)
delButton.pack(padx=10, pady=10)
root.mainloop()
成功解决tkinter