python学习tkinter列表框捕获无选择错误

2024-09-29 19:27:27 发布

您现在位置:Python中文网/ 问答频道 /正文

来自vba(我知道这不是最好的语言),但我很惊讶,当没有选择时,我无法在tkinter中轻松控制列表框表单(在vba列表表单中很容易做到)

#!/usr/bin/env python3
from tkinter import *
from tkinter import messagebox

class Application(Frame):

def __init__(self):
    super().__init__()
    self.create_widgets()

def create_widgets(self):
    self.master.title("Application")
    self.pack(fill=BOTH, expand=True)

    Label(self, text="First Name").grid(row=0,column=0)
    self.e1 = Entry(self)
    self.e1.grid(row=0, column=1)
    Label(self, text="Last Name").grid(row=1,column=0)
    self.e2 = Entry(self)
    self.e2.grid(row=1, column=1)
    Label(self, text="Age").grid(row=2, column=0)
    self.e3 = Entry(self)
    self.e3.grid(row=2, column=1)

    #Blank
    Label(self, text="").grid(row=2, column=0)

    Label(self, text="Gender").grid(row=0, column=4)
    self.f1=Frame(self, relief="sunken", borderwidth = 1)
    self.v=IntVar()

    self.r1=Radiobutton(self.f1, text="Male", variable=self.v, value=1).pack(anchor=W)
    self.r2=Radiobutton(self.f1, text="Female", variable=self.v, value=2).pack(anchor=W)
    self.f1.grid(row=1, column=4)

    Label(self, text="").grid(row=3)

    #Course Applied For
    Label(self, text="Course Applied for:", wraplength=60).grid(row=4)

    self.L1 = Listbox(self, width = 25, height = 4)

    Courses = [
    "Quality Management (Adv.)",
    "Financial Management (Adv.)",
    "Project Management (Adv.)",
    "Project Management (Int.)"
    ]

    for idx, item in enumerate(Courses):
        self.L1.insert(END, item)

    self.L1.grid(row=4, column=1)

    #Buttons
    self.f2=Frame(self)
    self.w=Button(self.f2, text ="Prerequisites", width=10, command=self.Chk_Prereq, default=ACTIVE).pack()
    self.w1=Button(self.f2, text ="Clear",  width=10, command=self.Clear).pack()
    self.w2=Button(self.f2, text ="Cancel", width=10, command=self.quit).pack()
    self.f2.grid(row=4, column=4)
    #Blank
    Label(self, text="").grid(row=6)
    #Checkbox
    self.var=IntVar()
    self.c=Checkbutton(self, text="Part-Time Course", variable=self.var, offvalue=0, onvalue=1)
    self.c.grid(row=7, column=0)


def Chk_Prereq(self):
    self.Eval()

def Eval(self):
    self.fname = self.e1.get()
    self.lname = self.e2.get()
    self.age = int(self.e3.get())
    #Check for Age
    if self.age < 21:
        messagebox.showwarning("Invalid Age",\
        "You are not eligible")
        return
    #Check for Gender
    if self.v.get()==1:
        self.str1 = "Dear Mr."
    elif self.v.get()==2:
        self.str1 = "Dear Ms."
    else:
        messagebox.showwarning("Missing Info", \
        "Please select the appropriate gender")
        return
    #Check for Prereq Course
    self.name = self.str1 + " " + self.fname + " " + self.lname
    self.varl1 = self.L1.get(self.L1.curselection())

    #if any(self.varl1.)

    if self.varl1 == "Quality Management (Adv.)":
        self.prereq = "The prereq for this course is Quality Management (Int)."
        self.flag = 1
    elif self.varl1 == "Financial Management (Adv.)":
        self.prereq = \
    "The prereq for this course is Financial Management (Bas)."
        self.flag = 1
    elif self.varl1 == "Project Management (Adv.)":
        self.prereq = \
    "The prereq for this course is Project Management (Int)."
        self.flag = 0
    #add1
    elif self.varl1 == "Project Management (Int.)":
        self.prereq = \
    "The prereq for this course is Project Management (Bas)."
        self.flag = 0
    #add11
    else:
        self.prereq = \
        "Please make a selection"
        self.flag = 0
    #Check whether Part Time
    if self.var.get() == 1 and self.flag == 0:
        self.str2 = "\nThis course is not available part time."
    elif self.var.get() == 1 and self.flag == 1:
        self.str2 = "\nThis course is available part time."
    else:
        self.str2 = ""
        self.result = self.prereq + self.str2
        messagebox.showinfo(self.name, self.result)

def Clear(self):
    self.e1.delete(0,END)
    self.e2.delete(0,END)
    self.e3.delete(0,END)
    self.c.deselect()
    self.L1.select_clear(self.L1.curselection())

def main():
    root = Tk()
    app = Application()
    root.mainloop()

if __name__ == '__main__':
    main()

它很好用

这是一个来自python2 ebook的脚本,有一些改动

问题是,当在课程列表框中没有选择时,我会在控制台窗口中收到一条错误消息,如下所示:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.8/tkinter/__init__.py", line 1883, in __call__
    return self.func(*args)
  File "/home/ananas/Documents/python scripts/py---2--tuto-tkinter/tuto_tk700.py", line 71, in Chk_Prereq
    self.Eval()
  File "/home/ananas/Documents/python scripts/py---2--tuto-tkinter/tuto_tk700.py", line 93, in Eval
    self.varl1 = self.L1.get(self.L1.curselection())
  File "/usr/lib/python3.8/tkinter/__init__.py", line 3182, in get
    return self.tk.call(self._w, 'get', first)
_tkinter.TclError: bad listbox index "": must be active, anchor, end, @x,y, or a number

def Eval(self)函数似乎可以捕捉到一个无列表框选择,但我尝试了空字符串条件和其他一些东西,因此有了self.prereq=“Please make a selection”,但没有实现。有什么帮助吗


Tags: textselfl1forgettkinterdefcolumn
2条回答

这是一个棘手的问题,因为检查下面的每一个值都不起作用

def Chk_Prereq(self):
    Courses = [
    "Quality Management (Adv.)",
    "Financial Management (Adv.)",
    "Project Management (Adv.)",
    "Project Management (Int.)"
    ]

    boo = 1

    self.varl1 = self.L1.get(self.L1.curselection())
    for idx, item in enumerate(Courses):
        if self.varl1 != item:
            boo = 0
        else:
            boo = 1

    if boo == 1:
        self.EvalInput()
    else: messagebox.showwarning("Course selection missing")

针对如下所示的变量类型进行检查也会失败

isinstance(self.L1.get(self.L1.curselection()), str)

所以我继续处理异常,我认为这在Python中很常见,在vba中不太常见,因为vba在这种情况下更灵活。我将能够看到listbox选择在内存中确切地引用了什么作为数据类型。Python在控制台窗口中抛出一条消息,该消息不会提供太多信息,并且会让用户想知道一个包含更多条目的表单缺少什么

使用异常处理对我来说是危险的,因为如果我看不到其他东西在那个块的内部或外部,我需要几个小时才能看到它在哪里。由于我正在开始学习,我(想)以后我会理解得更好(时间会证明的)。我输入的代码用于说明

#!/usr/bin/env python3
from tkinter import *
from tkinter import messagebox
    
class Application(Frame):

    def __init__(self):
        super().__init__()
        self.create_widgets()

    def create_widgets(self):
        #Label(master, text="First Name").grid(row=0)
        self.master.title("Application")
        self.pack(fill=BOTH, expand=True)

        Label(self, text="First Name").grid(row=0,column=0)
        self.e1 = Entry(self)
        self.e1.grid(row=0, column=1)
        Label(self, text="Last Name").grid(row=1,column=0)
        self.e2 = Entry(self)
        self.e2.grid(row=1, column=1)
        Label(self, text="Age").grid(row=2, column=0)
        self.e3 = Entry(self)
        self.e3.grid(row=2, column=1)

        #Blank
        Label(self, text="").grid(row=2, column=0)

        Label(self, text="Gender").grid(row=0, column=4)
        self.f1=Frame(self, relief="sunken", borderwidth = 1)
        self.v=IntVar()

        self.r1=Radiobutton(self.f1, text="Male", variable=self.v, value=1).pack(anchor=W)
        self.r2=Radiobutton(self.f1, text="Female", variable=self.v, value=2).pack(anchor=W)
        self.f1.grid(row=1, column=4)

        Label(self, text="").grid(row=3)

        #Course Applied For
        Label(self, text="Course Applied for:", wraplength=60).grid(row=4)

        self.L1 = Listbox(self, width = 25, height = 4)

        Courses = [
        "Quality Management (Adv.)",
        "Financial Management (Adv.)",
        "Project Management (Adv.)",
        "Project Management (Int.)"
        ]

        for idx, item in enumerate(Courses):
            self.L1.insert(END, item)

        self.L1.grid(row=4, column=1)

        #Buttons
        self.f2=Frame(self)
        self.w=Button(self.f2, text ="Prerequisites", width=10, command=self.Chk_Prereq, default=ACTIVE).pack()
        self.w1=Button(self.f2, text ="Clear",  width=10, command=self.Clear).pack()
        self.w2=Button(self.f2, text ="Cancel", width=10, command=self.quit).pack()
        self.f2.grid(row=4, column=4)
        #Blank
        Label(self, text="").grid(row=6)
        #Checkbox
        self.var=IntVar()
        self.c=Checkbutton(self, text="Part-Time Course", variable=self.var, offvalue=0, onvalue=1)
        self.c.grid(row=7, column=0)


def Chk_Prereq(self):
    self.EvalInput()

def EvalInput(self):
    self.fname = self.e1.get()
    self.lname = self.e2.get()
    self.age = int(self.e3.get())
    #Check for Age
    if self.age < 21:
        messagebox.showwarning("Invalid Age",\
        "You are not eligible")
        return
    #Check for Gender
    if self.v.get()==1:
        self.str1 = "Dear Mr."
    elif self.v.get()==2:
        self.str1 = "Dear Ms."
    else:
        messagebox.showwarning("Missing Info", \
        "Please select the appropriate gender")
        return
    #Check for Prereq Course
    self.name = self.str1 + " " + self.fname + " " + self.lname

    try:
        self.varl1 = self.L1.get(self.L1.curselection())

        if self.varl1 == "Quality Management (Adv.)":
            self.prereq = "The prereq for this course is Quality Management (Int)."
            self.flag = 1
        elif self.varl1 == "Financial Management (Adv.)":
            self.prereq = \
        "The prereq for this course is Financial Management (Bas)."
            self.flag = 1
        elif self.varl1 == "Project Management (Adv.)":
            self.prereq = \
        "The prereq for this course is Project Management (Int)."
            self.flag = 0
        else:
            self.prereq = \
            "The prereq for this course is Project Management (Bas)."
            self.flag = 0
        #Check whether Part Time
        if self.var.get() == 1 and self.flag == 0:
            self.str2 = "\nThis course is not available part time."
        elif self.var.get() == 1 and self.flag == 1:
            self.str2 = "\nThis course is available part time."
        else:
            self.str2 = ""
            self.result = self.prereq + self.str2
            messagebox.showinfo(self.name, self.result)

    except:
        self.prereq = "No course selection made"
        self.result = self.prereq
        messagebox.showinfo(self.name, self.result)

def Clear(self):
    self.e1.delete(0,END)
    self.e2.delete(0,END)
    self.e3.delete(0,END)
    self.c.deselect()
    self.L1.select_clear(self.L1.curselection())



def main():
    root = Tk()
    app = Application()
    root.mainloop()

if __name__ == '__main__':
    main()

感谢您的上述评论,但我认为处理异常是唯一的答案。请张贴完整的代码,如果这不是tk listbox的未来使用可能会有帮助的情况,我会将其标记为答案和投票

第一:Eval在python中已经是一个函数,所以可能需要更改名称

第二行(第93行):如果我认为这是正确的,您将尝试查询选择。但是如果没有选择任何内容,则无法从curseelection()函数返回任何内容

改变

self.varl1 = self.L1.get(self.L1.curselection())

if self.L1.curselection() == ():
    #NOTHING IS SELECTED, MAYBE THROW AN ERROR
else:
    self.varl1 = self.L1.get(self.L1.curselection())

编辑:选中“”但一条注释告诉我该函数返回一个tulple而不是字符串

相关问题 更多 >

    热门问题