python - tkinter 从菜单中显示新框架
问题描述
我正在尝试在 python 和 tkinter 中编写我的第一个脚本。
当从菜单栏按钮单击时,我阻止显示函数(def onDisplay )的新框架,但没有附加任何内容。没有错误显示:-(
新框架由文本文件中的动态复选框组成:txt 文件:
item1
item2
...
item100
GUI的屏幕:
这是我的代码:
from tkinter import Tk, Frame, Menu, Checkbutton, Text, TOP, BOTH, X, N, LEFT, BooleanVar
from tkinter.ttk import Frame, Label, Entry
import glob
class Example(Frame):
def __init__(self):
super().__init__()
self.initUI()
#self.display_srv()
def initUI(self):
self.master.title("Submenu")
menubar = Menu(self.master)
self.master.config(menu=menubar)
fileMenu = Menu(menubar)
submenu = Menu(fileMenu)
submenu.add_command(label="lst1", command=self.onDisplay)
submenu.add_command(label="lst2")
submenu.add_command(label="lst3")
fileMenu.add_cascade(label='Listing', menu=submenu, underline=0)
fileMenu.add_separator()
fileMenu.add_command(label="Exit", underline=0, command=self.onExit)
menubar.add_cascade(label="File", underline=0, menu=fileMenu)
#The frame i tried to display
def onDisplay(self):
self.master.title("display it")
self.pack(fill=BOTH, expand=True)
frame1 = Frame(self)
frame1.pack(fill=X)
path = '/root/liste/*.txt'
files=glob.glob(path)
count = 0
for file in files:
with open(file, 'r') as lst_file:
for item in lst_file:
# Need to split all item by 10
Checkbutton(self, text=item.rstrip()).grid(row=count//10, column=count%10)
count += 1
def onClick(self):
if self.var.get() == True:
self.master.title("Checkbutton")
else:
self.master.title("")
def onExit(self):
self.quit()
def main():
root = Tk()
root.geometry("850x550+300+300")
app = Example()
root.mainloop()
if __name__ == '__main__':
非常感谢您的帮助
问候,
解决方案
主要问题是您正在混合grid
并pack
在同一个父容器中。您正在调用pack
,frame1
但您正在调用grid
检查按钮,并且它们都有self
.
那是行不通的,因为每一个都grid
将pack
尝试根据它的规则调整容器的大小,触发另一个根据它的规则重新配置,依此类推,直到时间结束。
因此,只需在复选按钮上更改对.grid(...)
to的调用即可.pack(...)
解决该问题。
我的猜测是你打算把检查按钮放在里面frame1
。如果是这种情况,您需要将检查按钮指定frame1
为主控。为了便于阅读和调试,我还建议将调用grid
放在单独的行上。有了它,您可以继续使用grid
复选按钮和pack
其他所有内容。
cb = Checkbutton(frame1, text=item.rstrip())
cb.grid(row=count//10, column=count%10)
推荐阅读
- python - Python Pandas:通过重复项将一列分组并在相应列中连接字符串
- pdf-generation - 在 Joomla 组件中创建 PDF 文件时,外部参照表损坏
- python - userpost() 得到了一个意外的关键字参数“实例”
- javascript - 如何通过以字符串或数组形式给出的自定义顺序对对象数组进行排序?
- python - 如何设置 LSTM 向量输入和输出的大小
- php - 如何检查数组值是否匹配,同时在 PHP 中保留其顺序
- mysql - 选择不同日子的最低/最高温度
- javascript - 组件返回未定义
- javascript - Javascript纸牌游戏:一旦使用卡片,就不再使用卡片?
- python-3.x - 从输入 import Any, Tuple, Deque ImportError: cannot import name 'Deque'