Why can't I see the messagebox when input is not a, b, or c? I am sure there is a good reason but I guess I can't find out yet.
Thanks.
from tkinter import*
from tkinter import messagebox
def math():
while True:
data=input("enter a,b or c ")
if data=='a':
data=5
elif data=='b':
data=10
elif data=='c':
data=15
else :
hi=messagebox.showerror(title="Try",message="Wrong Input ")
data=0
print(data)
math()
Because you are not running tkinter. You need to call Tk() mainloop().
It's bad practice to do wildcard import e.g.(from tkinter import *)
You don't need to assign
messagebox
to a variable. Just call
messagebox.showerror
straight away.
As @
menator01 said, it's bad practice to import everything from a module. In this case, you don't even need to import anything else than
messagebox
.
Also, don't forget to break from the
while
loop or you will be stuck in it forever.
from tkinter import messagebox
def math():
while True:
data = input("enter a,b or c ")
if data == 'a':
data=5
elif data == 'b':
data=10
elif data == 'c':
data=15
else:
messagebox.showerror(title="Try",message="Wrong Input")
data=0
print(data)
break
if __name__ == "__main__":
math()
Here is an example of your code modified
from tkinter import messagebox
def func():
while True:
data = input('enter a, b, or c. To quit enter q\n>> ')
if data == 'a':
data = 5
elif data == 'b':
data = 10
elif data == 'c':
data = 15
elif data == 'q':
print('Goodbye!')
break
else:
messagebox.showerror(title='Error', message='Wrong Input')
data = 0
print(f'data was set to {data}\n')
func()
@
carecavoador
Sorry, just realized my code is the same as yours.
You cannot create a message box without first calling Tk(). mainloop() is not required. I just ran a test to verify. You can unmap the window created by Tk().
import tkinter as tk
from tkinter import messagebox
def func():
while True:
data = input('enter a, b, or c. To quit enter q\n>> ')
if data == 'a':
data = 5
elif data == 'b':
data = 10
elif data == 'c':
data = 15
elif data == 'q':
print('Goodbye!')
break
else:
messagebox.showerror(title='Error', message='Wrong Input')
data = 0
print(f'data was set to {data}\n')
root = tk.Tk()
root.withdraw()
func()
I removed the tkinter import and didn't call tk. Just used the from tkinter import messagebox. Worked in vs studio and terminal. On Ubuntu. My first attempt was the setup you have for the code calling tk.
Interesting. Doesn't work for me on Windows using either vscode or powershell. A message box pops up, but so does an empty tkinter window.