【问题标题】:How to not send an error message when a cancel button is pressed in 'simpledialog.askstring' window?在“simpledialog.askstring”窗口中按下取消按钮时如何不发送错误消息?
【发布时间】:2019-04-18 23:26:03
【问题描述】:

所以我目前正在尝试制作一个程序,允许我输入一个字符串,该字符串输出到 tkinter 中的文本窗口。但是,当在 simpledialog.askstring 窗口中按下“取消”按钮时,我收到一条错误消息。

这是我在 Python Shell 中收到的错误消息:

_tkinter.TclError: wrong # args: should be ".!text insert index chars ?tagList chars tagList ...?"

我只是想让程序在按下取消按钮时什么都不做。 :(

from tkinter import *
from tkinter import simpledialog
import tkinter.messagebox

class Thing:
    def __init__(self):
        global buttonThing
        global window
        window = Tk()

        frame1 = Frame(window)
        frame1.pack()
        buttonThing = Button(frame1, text = "click me", command = self.clickMe)
        buttonThing.pack()
        self.text =Text(window)
        self.text.pack()
        window.mainloop()


    def clickMe(self):
        uwu = simpledialog.askstring("hey","put stuff")

        self.text.insert(END, uwu)



Thing()

【问题讨论】:

    标签: python python-3.x tkinter


    【解决方案1】:

    当您按下取消时,您的对话框返回 None 并且当您尝试在文本控件中插入 None 时存在错误

    所以用这个替换这个代码self.text.insert(END, uwu)

    if uwu: 
        self.text.insert(END, uwu)
    

    【讨论】:

      【解决方案2】:

      您总是可以在 try: except: 块中运行它,如下所示:

      def clickMe(self):
          try:
              uwu = simpledialog.askstring("hey","put stuff")
              self.text.insert(END, uwu)
      
          except Exception:
              pass
      

      但正确的方法是按照@Mahmoud Elshahat 回复的方式行事

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-06
        • 1970-01-01
        • 1970-01-01
        • 2021-12-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多