我正在尝试创建一个包含带滚动条的列表框的弹出窗口。但是,我不明白为什么在Python中运行代码时没有显示任何内容。一如既往,非常感谢!
from Tkinter import *
def run():
# create the root and the canvas
root = Tk()
canvasW, canvasH = 300, 200
canvas = Canvas(root, width=canvasW, height=canvasH)
canvas.pack()
class Struct: pass
canvas.data = Struct()
init(canvas)
root.mainloop()
def init(canvas):
master = Tk()
# use width x height + x_offset + y_offset (no spaces!)
master.geometry("240x180+130+180")
# create the listbox (height/width in char)
listbox = Listbox(master, width=20, height=6)
listbox.grid(row=0, column=0)
# create a vertical scrollbar to the right of the listbox
yscroll = Scrollbar(command=listbox.yview, orient=VERTICAL)
yscroll.grid(row=0, column=1, sticky='ns')
listbox.configure(yscrollcommand=yscroll.set)
# now load the listbox with data
numbers = ["1", "2", "3"]
for item in numbers:
# insert each new item to the end of the listbox
listbox.insert(END, item)
run()
答案 0 :(得分:0)
问题(或问题的一部分)是您正在创建Tk
类的两个实例。 tkinter程序只需要Tk
的一个实例。
答案 1 :(得分:0)
正如Bryan Oakley先前所说,部分问题是Tk
类的多个实例。我认为Canvas
对象也是不必要的。这是一个简单的案例:
from Tkinter import *
class MyList(object):
def __init__(self, master=None):
self.master = master
self.yscroll = Scrollbar(master, orient=VERTICAL)
self.yscroll.pack(side=RIGHT, fill=Y)
self.list = Listbox(master, yscrollcommand=self.yscroll.set)
for item in xrange(100):
self.list.insert(END, item)
self.list.pack(side=LEFT, fill=BOTH, expand=1)
self.yscroll.config(command=self.list.yview)
def run():
root = Tk()
app = MyList(root)
root.mainloop()
run()