Here I am using from tkinter import * inside a function and when I am running the code it is showing me a SyntaxError.
Please tell me how I can use from tkinter import * inside a function.
You should move the import statements to the beginning of the file, at the top. You are also importing tkinter twice.
Related
This question already has answers here:
Difference between import tkinter as tk and from tkinter import
(3 answers)
How do I import other Python files?
(23 answers)
Closed 4 years ago.
Can someone please explain the difference between
import tkinter as tk
and
from tkinter import *
It would be so great if someone could give and example where the same task is
achieved (or an object is created) by using these two statements seperately
Simply saying, the import tkinter as tk will initiate a tk instance of tkinter in your file which can call it's functions by writing something like
tk.Entry()
Which will save you from typing the long name.
while from tkinter import * will import all the names defined under the __all__ variable, so you can call the same function as
Entry()
You should read This to understand more
Both are importing the same package. The primary difference is that your first line is importing the package tkinter and then referring to it with "tk", which would allow you to call its functions using that different name. I don't have any experience with tkinter, but a good example I can give would be with numpy or pandas. A lot of functions in numpy, like numpy.random.randn() could instead be written with a shorthand name using "import as", like so:
import numpy as np
np.random.randn()
The differences seams little at first however import tkinter as tk is actually a much better option for one big reason.
By importing as something specific you make all the methods from that import required a prifix. This prevents methods from overriding or being overwritten accidentally.
For example if I have a library that contains a time() method and say lest call this library custom_timer and then say I need to import the built in time method also.
If use * for my import we have a problem.
from custom_timer import * # importing all modules including time() form this library.
import time # importing built in time().
What will end up happening is the 2nd import will override the time method from the first import. To prevent accidents like this we can simple import as your_prefix_here.
Take this example.
import custom_timer as ct # importing this library as ct.
import time # importing built in time().
In this case we will have 2 distinctive imports for time that do not override each other.
One is ct.time() and the other is time()
Because libraries like tkinter contain many methods it is safer to use import as verses import * for the above reason.
All that said if you are in a hurry and just want to throw something together to test an idea or answer a question using from tkinter import * is fine for much smaller applications. Personally I try to use import tkinter as tk for everything I do for good practice.
As for your request for 2 examples see below.
With tk import:
import tkinter as tk
root = tk.Tk()
tk.Label(root, text="I am a label made using tk prefix.")
root.mainloop()
With * import:
from tkinter import *
root = Tk()
Label(root, text="I am a label made in tkinter with the * import.")
root.mainloop()
How to clear a listbox when a button is clicked to re-populate it? The code below is giving me an error.
code:
self.listNodes.delete(0,END)
error:
NameError: name 'END' is not defined
Depending on how you imported tkinter you may have to put end in quotations
Try:
self.listNodes.delete(0,'end')
you can also use:
self.listNodes.delete(0,tk.END)
Replace:
self.listNodes.delete(0,END)
with:
self.listNodes.delete('0','end')
END is a variable of tkinter module, which suggests either a wildcard(from tkinter import *) import or from tkinter import END was supposed to be used.
You can use this is you imported tkinter as:
import tkinter as tk
self.listnodes.delete(0, tk.END)
Or you can do:
from tkinter import *
self.listnodes.delete(0, END)
Destruction is the best way to delete something.
self.listNode.destroy()
and then add Your data again to your ListBox.
You can Distroy list node like this
from tkinter import *
self.listnodes.delete(0, END) *
I thought that
from tkinter import *
imports all names into my current file's namespace so that I can access all of it directly. However, I get an error on instantiating a message box:
messagebox.showinfo("Something")
Once I add
from tkinter import messagebox
all works fine. I don't understand why. Didn't the first import statement already import all names in the tkinter module including messagebox?
Importing a module (tkinter) does not automatically import submodules (tkinter.messagebox) unless the module do it explicitly for you.
messagebox is a submodule of tkinter.
You should import module "messagebox"
(use "import ... as ..." to make it shorter)
import tkinter.messagebox
tkinter.messagebox.showinfo("Something")
Or as you figured out yourself,
from tkinter import messagebox
Since messagebox is a file inside the Tkinter module, you won't be able to access it by just calling Tkinter. To import the submodules you have to call out the specific files like this:
from tkinter import messagebox
In my past programming i used the following code:
from tkinter import *
Gui = Tk()
but someone told me that importing * was not good for many reasons but now when i want to import
from tkinter import geometry
it says geometry not a module thing (name).
and when i do:
import tkinter
tkinter.geometry(500x500)
it says 'module' object has no attribute 'geometry'
Can someone explain me how to import with tkinter all the different ways?? Not only for geometry but most of the tkinter modules...???
That's because the module tkinter doesn't have a geometry function. It's the Tk instances that do.
Here's a good way to accomplish what you're trying to do:
import tkinter as tk # tk is a convenient, easy to type alias to use for tkinter.
gui = tk.Tk()
gui.geometry("500x500") # don't forget the quotes
Why from tkinter import * is a non-ideal way to import tkinter
As an aside, whoever told you that from tkinter import * was a bad idea was correct - when you do that, you load all of tkinter's namespace into your module's namespace.
If you do that, you can end up with unpleasant namespace collisions, like this:
from tkinter import *
gui = Tk()
Label = "hello"
Label1 = Label(gui, text=Label)
# Traceback (most recent call last):
# File "stackoverflow.py", line 98, in <module>
# Label1 = Label(gui, text=Label)
# TypeError: 'str' object is not callable
You've overwritten the reference to tkinter's Label widget - so you can't create any more Labels! Of course you shouldn't be capitalizing local variables like that anyways, but why worry about avoiding those namespace problems when you can do this instead:
import tkinter as tk
This ^^^^ import method is also preferable because if at some point you want to swap Tkinter out for another module with a similar implementation, instead of combing through your code for all elements of the Tkinter module, you can just go like this:
#import tkinter as tk
import newTkinter as tk
And you're all set. Or, if you want to use another module that happens to have some of the same names for its classes and methods, the following would cause chaos:
from tkinter import *
from evilOverlappingModule import *
but this would be fine:
import tkinter as tk
import evilOverlappingModule as evil
The reason that from module import * is considered harmful is that it pollutes the main namespace with every public name in the module. At best this makes code less explicit, at worst, it can cause name collisions. For example, module codecs has an open method defined, and there is the built-in version, which take different arguments. If I write
from codecs import *
f = open(…)
which open will I get? Tkinter has a lot of symbols, and tkinter based programs tend to use them very heavily. better than the import * is
import tkinter as tk
which then allows the — still explicit, but easier to type and read:
tk.Tk().geometry(…)
If you * imported tkinter, essentially tkinter. is in the namespace, meaning that to access to tkinter modules without worrying about prefixing it with tkinter.. In this case, geometry("500x500") is a method of Tk(), so you would use it like this
from Tkinter import *
Gui = Tk()
Gui.geometry("500x500")
Gui.mainloop()
Similar objects, such as various widgets, etc. are used the same. For example, a label would be made like this:
from Tkinter import *
Gui = Tk()
label= Label(Gui, text="Hello World!")
label.pack()
Gui.mainloop()
I don't know why someone said that importing * wasn't good cause that isn't true, it's actually better then just importing tkinter. Importing * will make the programming easier. With just tkinter you would need to type tkinter. before doing something, or if you do it as tk, you would need to do tk., from tkinter import * is the best what you can do.
Instead of doing:
from tkinter import *
You can do:
from tkinter import Tk, Canvas #The widgets you want to use
Or:
import tkinter as tk
Here’s a quick answer: Tkinter doesn’t have a geometry function. You can use the geometry function with instances of the Tk() class.
Example:
import tkinter as tk # Use the module name ’Tkinter’ if you have Python 2
root = tk.Tk()
root.geometry(‘500x500’) # You can change the size
# Other code goes here
root.mainloop()
Just like the geometry function, the mainloop, pack, grid, place, config etc. functions are used with the instances of the class Tk()
Thank You! Hope that works!
The following is a function I created, and put it in a file called last_function.py
from tkinter import*
def new_gui(app,sound_file,mixer):
track=mixer.Sound(sound_file)
def track_toggle():
if ballCheckbutton.get()==1:
track.play(loops=-1)
else:
track.stop()
ballCheckbutton=IntVar()
c1=Checkbutton(app,text="check me out",command=track_toggle,variable=ballCheckbutton)
c1.pack(side=LEFT)
ballScale=DoubleVar()
def ScaleVolume(v):
track.set_volume(ballScale.get())
ballScale.set(track.get_volume())
s1=Scale(app,variable=ballScale,resolution=0.1,command=ScaleVolume,orient=HORIZONTAL,from_=0.0,to=1.0,label="volume")
s1.pack()
and this is the file i use.. to call the code and run it..
from tkinter import *
import pygame.mixer
from last_function import*
app=Tk()
mixer=pygame.mixer
mixer.init()
new_gui(app,"49119_M_RED_HardBouncer.wav",mixer)
def close():
mixer.stop()
app.destroy()
app.protocol("WM_DELETE_WINDOW",close)
app.mainloop()
Everything works fine.. but my query is...
1> Why can't I remove from tkinter import* from the last_function file.. cause anyway it's got that on the top of the file that's calling it right. Why do I get an error saying IntVar() not defined.
2> Why do I have to pass mixer as a parameter in the function? can the function not inherit it directly from import pygame.mixerthat's on top of the file calling it?
What I mean to say is. THERE ARE TKINTER COMPONENTS ALSO BEING USED, BUT I DON'T PASS TKINTER AS A PARAMETER.. Do I ! then why is there this... selective parameter assignment??
I'm really confused!!!
1> Why can't i remove from tkinter
import* from the last_function file..
cause anyway it's got that on the top
of the file that's calling it
right.Why do i get an error saying
IntVar() not defined
The Python "import" follows the same scoping rules as the rest of the Python language. By "import" at the top of your second files does not make the Tkinter namespace available to the last_function.py module. Tkinter also needs to be imported there.
2>why do i have to pass mixer as a
parameter in the function? can the
function not inherit it directly from
import pygame.mixerthat's on top of
the file calling it? WHAT I MEAN TO
SAY IS. THERE ARE TKINTER COMPONENTS
ALSO BEING USED,BUT I DON'T PASS
TKINTER AS A PARAMETER.. DO I!! then
why is there this.. selective
parameter assignment??
With the way you have this coded, you need to pass mixer because you are modifying it in your second file with:
mixer.init()
If you reimported mixer in your last_function.py, you would be getting another instance of mixer and not the one previously imported. There is nothing selective about this since both of your files have the Tkinter namespace imported.
You should try and re-factor this code to avoid having to import Tkinter into two modules and having to init mixer in one module and pass it to another.