'How to not send an error message when a cancel button is pressed in 'simpledialog.askstring' window?
So I am currently trying to make a program that allows me to enter a string which outputs to a text window in tkinter. However, I am getting an error message when the 'cancel' button is pressed in the simpledialog.askstring window.
this is the error message that I am getting in the Python Shell:
_tkinter.TclError: wrong # args: should be ".!text insert index chars ?tagList chars tagList ...?"
I just wanted the program to do nothing when the cancel button is pressed. :(
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()
Solution 1:[1]
your dialogbox returned None when you press cancel and the error exist when you tried to insert None in text control
so replace this code self.text.insert(END, uwu)
with this
if uwu:
self.text.insert(END, uwu)
Solution 2:[2]
You could always run it in a try: except:
block, like so:
def clickMe(self):
try:
uwu = simpledialog.askstring("hey","put stuff")
self.text.insert(END, uwu)
except Exception:
pass
But the proper way would be to do what @Mahmoud Elshahat replied
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mahmoud Elshahat |
Solution 2 | CodeWizard777 |