Question 1: I have a non useful window that appears when using tkinter in spyder. Any solution for this issue ?
Question 2: Why there is a warning message on 'from tkinter import *' ?
Code:
from tkinter import *
from tkinter.simpledialog import askstring
from tkinter import messagebox
box = Tk()
name = askstring('Name','What is your name?')
messagebox.showinfo('Hello!','Hi, {}'.format(name))
box.mainloop()
CodePudding user response:
The "non useful" window is simply box
.
messagebox
will open a new window. So you can just remove box
if you don't intend to use it further.
It's usually not recommended to import everything from a module because it could cause name conflicts with other modules or built-in function:
import tkinter as tk
from tkinter.simpledialog import askstring
name = askstring('Name','What is your name?')
tk.messagebox.showinfo('Hello!','Hi, {}'.format(name))
CodePudding user response:
The additional window is the instance of Tk
most often named root cause every other window or widget is a child of the root window. You will need it to initiate your messagebox
but if you don't want to look at it you have several choices.
My personal recommendation is to us overrideredirect
which will discard it from the taskbar and use withdraw
to actually hide it in the screen/monitor. But you may prefer wm_attributes('-alpha', 0)
over it to make it opaque/transparent.
Avoiding wildcard imports is recommanded because of name clashes/collisions. For example tkinter has a PhotoImage
class, so does pillow
. If you have wildcard imports on both, on PhotoImage will overwrite the other in the global namespace.
Code:
import tkinter as tk
from tkinter.simpledialog import askstring
from tkinter import messagebox
box = tk.Tk()
box.overrideredirect(True)
box.withdraw()
name = askstring('Name','What is your name?') #blocks the code block
messagebox.showinfo('Hello!','Hi, {}'.format(name)) #shows message
box.after(5000, box.destroy) #destroy root window after 5 seconds
box.mainloop()#blocks until root is destroyed
CodePudding user response:
For the first question answer is that you don't need to create box
because function askstring
create frame on it's own. So if the whole program is just to ask for the name and to greet user, you are perfectly fine with just this piece of code:
from tkinter import *
from tkinter.simpledialog import askstring
from tkinter import messagebox
name = askstring('Name','What is your name?')
messagebox.showinfo('Hello!','Hi, {}'.format(name))
And for the second question you need to post what warning you get.