添加框架小部件时,Tkinter gui停止运行

时间:2015-08-05 20:14:29

标签: python tkinter tkinter-canvas

以下是我用于项目的一些代码,此时它非常简单且无法正常运行。我在使用框架小部件时遇到了麻烦。现在当我运行代码时没有任何反应,但是如果我删除关于框架和滚动条的线条,并将listbox / canvas小部件父级更改为" root"而不是#34; frame",代码有效。我在网上看了很多例子,当我试图把所有东西放在一个框架而不是根窗口时,我不明白为什么没有gui窗口出现......?谢谢!

使用python 2.7。

import pymongo
import glob, os
import Tkinter
from Tkinter import *
from PIL import Image, ImageTk

root = Tkinter.Tk()
root.title("keyBuilder")
frame = Frame(root, width = 630, height = 400)

groupMenu = Listbox(frame)
groupMenu.config(width = 30)
groupMenu.insert(END, "Group 1")
groupMenu.insert(END, "Group 2")
groupMenu.insert(END, "Group 3")

yscrollbar = Scrollbar(frame)
yscrollbar.grid(row=0, column=1, sticky=N+S)

gallery = Canvas(frame, width = 600, height = 400, yscrollcommand = yscrollbar.set)

path = r'/Users/Sam/Desktop/keynoteProject/slideIcons'
COLUMNS = 6
image_count = 0

for infile in glob.glob(os.path.join(path, '*.jpeg')):
    image_count += 1
    r, c = divmod(image_count-1, COLUMNS)
    im = Image.open(infile)
    resized = im.resize((100, 100), Image.ANTIALIAS)
    tkimage = ImageTk.PhotoImage(resized)
    myvar = Label(gallery, image=tkimage)
    myvar.image = tkimage
    myvar.grid(row=r, column=c)

groupMenu.pack(side = LEFT, fill = Y)
gallery.pack(side = RIGHT)
frame.pack()

root.mainloop()

如果它有用,则此代码有效:

import pymongo
import glob, os
import Tkinter
from Tkinter import *
from PIL import Image, ImageTk

root = Tkinter.Tk()
root.title("keyBuilder")

groupMenu = Listbox(root)
groupMenu.config(width = 30)
groupMenu.insert(END, "Group 1")
groupMenu.insert(END, "Group 2")
groupMenu.insert(END, "Group 3")

gallery = Canvas(root, width = 600, height = 400)

path = r'/Users/Sam/Desktop/keynoteProject/slideIcons'
COLUMNS = 6
image_count = 0

for infile in glob.glob(os.path.join(path, '*.jpeg')):
    image_count += 1
    r, c = divmod(image_count-1, COLUMNS)
    im = Image.open(infile)
    resized = im.resize((100, 100), Image.ANTIALIAS)
    tkimage = ImageTk.PhotoImage(resized)
    myvar = Label(gallery, image=tkimage)
    myvar.image = tkimage
    myvar.grid(row=r, column=c)

groupMenu.pack(side = LEFT, fill = Y)
gallery.pack(side = RIGHT)

root.mainloop()

1 个答案:

答案 0 :(得分:1)

问题在于您将packgrid混合在同一个容器中。您只能将一个或另一个用于共享公共父级的所有窗口小部件。 groupMenuyscrollbarcanvas都是frame的孩子。 yscrollbar使用grid但其他人使用pack