Python Tkinter按钮包问题

时间:2017-01-04 14:31:42

标签: python python-3.x tkinter

到目前为止我总共有5个按钮,我试图在我的主页上显示其中三个按钮隐藏另外两个按钮然后当我选择我的按钮'file_cleanup'按钮1,2和& 3应该隐藏和按钮4& 5出现。我想我明白为什么我的错误发生但我不知道或者可以找到解决方法。

代码:

from tkinter import *
from tkinter.filedialog import askopenfilenames
from main_code import *

import sys


OPTIONS = [
    "Homepage",
    "Instructions"
]


root = Tk()
root.title('Title')
root.geometry('700x300')

var = StringVar(root)
var.set = ('Menu')

menu = OptionMenu(root, var, *OPTIONS)
menu.pack(side=TOP, anchor=W)



separator = Frame(height=2, bd=1, relief=SUNKEN)
separator.pack(fill=X, padx=1, pady=20)
top = Frame(root)
center = Frame(root)
bottom = Frame(root)
top.pack(side=TOP)
center.pack(side=TOP)
bottom.pack(side=BOTTOM, fill=BOTH, expand=True)


#Method changes GUI when an option from menu is selected

def change_layout(*args):
    if var.get() == "Homepage":
        b1.pack(in_=center, side=LEFT)
        b2.pack(in_=center, side=LEFT)
        b3.pack(in_=center, side=LEFT)
        b4.pack_forget()
        b5.pack_forget()
    if var.get() == "Instructions":
        b1.pack_forget()
        b2.pack_forget()
        b3.pack_forget()



def load_file():
    fname = askopenfilenames(filetypes= (("Text Files", ".txt"),
                            ("HTML Files", "*.html;*.htm"),
                                ("All Files", "*.*")))

    if fname:
        try:
            print('Files loaded')
        except OSError as Error:
            print('Files encountered error while loading')


def file_cleanup():
    b1.pack_forget()
    b2.pack_forget()
    b3.pack_forget()
    b4 = Button(root, text='Clean chat file', height=5, command=load_file)
    b5 = Button(root, text='Clean lex file', height=5, command=load_file)
    b4.pack(in_=center, side=LEFT)
    b5.pack(in_=center, side=LEFT)

var.trace('w', change_layout)

# widgets for the top part of the GUI
b1 = Button(root, text='File Cleaner', height=5, command=file_cleanup)
b1.place(x=170, y=500)
b2 = Button(root, text='Run Program', height=5)
b3 = Button(root, text='Save Results', height=5)



b1.pack(in_=center, side=LEFT)
b2.pack(in_=center, side=LEFT)
b3.pack(in_=center, side=LEFT)

b4 = Button(root, text='Clean chat file', height=5, command=load_file)
b5 = Button(root, text='Clean lex file', height=5, command=load_file)


#Instructions - TODO Later date


root.mainloop()

错误讯息:

Traceback (most recent call last):
  File "C:/Users/Lewis Collins/PycharmProjects/program_w_gui/Home.py", line 74, in <module>
    b1 = Button(root, text='File Cleaner', height=5, command=file_cleanup())
  File "C:/Users/Lewis Collins/PycharmProjects/program_w_gui/Home.py", line 65, in file_cleanup
    b1.pack_forget()
NameError: name 'b1' is not defined

如果你想知道为什么我宣布b4&amp; b5两次是因为如果我没有在那里声明它们,file_cleanup会发回错误。这是我第一次在3.5中使用Tkinter,与我在2.7上使用tkinter的类似工作相比,我收到的错误差异实际上是在降低我的工作速度。

非常感谢所有帮助和反馈, 提前谢谢。

0 个答案:

没有答案