Am trying to run this code ,but its saying tkinter has no attribute "Tk()",am using pycharm,both the Tk() and mainloop(). Thank you - python-3.x

Am trying to run this code ,but its saying tkinter has no attribute “Tk()”,am using pycharm,both the Tk() and mainloop(). Thank you
import tkinter
def main():
main_window=tkinter.Tk() #here
tkinter.mainloop() #and here
main()

Related

Converting Python 2.7 to Python 3 with tkinter

I have a working application using Python 2.7 and Tkinter that uses these constructs:
from Tkinter import *
import Tkinter
import tkFileDialog
class Window(Frame):
#...
# other functional code
#...
def ChangeCWD(self): #CWD is current working directory
root = Tkinter.Tk()
root.withdraw()
directory = tkFileDialog.askdirectory( ... )
root = Tk()
root.mainloop()
It has labels, buttons, canvas, multiple frames and file dialogue boxes and it all works nicely.
I have begun updating the code to work on Python 3.5 and, so far all functions seem to work except for the file dialog. This is where I have got to so far:
from tkinter import *
import tkinter
import tkinter.filedialog
class Window(Frame):
#...
# other functional code
#...
def ChangeCWD(self): #CWD is current working directory
root = tkinter.Tk()
root.withdraw()
directory = filedialog.askdirectory( ... )
root = Tk()
root.mainloop()
However this code produces the error
"NameError: name 'filedialog' is not defined"
when the filedialog.askdirectory() statement is reached. Could anyone provide any help to understand what I should do to correct the situation please?
As an aside, please be gentle with me! I've always been rather mystified by the various ways of invoking import statements and how to use "tk." or "root." before some function calls. There are simply too many conflicting explanations out on the web that I can't get a clear picture.
You use import tkinter.filedialog, which imports tkinter.filedialog with the namespace tkinter.filedialog, then you try to use filedialog in your code.
Pick one of these two:
change your call to tkinter.filedialog.askdirectory( ... )
change your import to import filedialog from tkinter, which will import tkinter.filedialog with the namespace filedialog.
Note: from tkinter import * might seem like it should import filedialog, but that * does not import submodules unless the package has explicitly specified that they should.

Tkinter textvariable does not work in a secondary window?

Because when I use textvariable from a secondary window called from a command in another window the variable.set () is not reflected in that secondary window.
example:
import tkinter as tk
def test():
ven=tk.Tk()
v1=tk.StringVar()
v1.set('TEST')
print(v1.get())
tk.Label(ven, textvariable=v1).pack()
ven.mainloop()
win=tk.Tk()
tk.Button(text='BOTON',command=test).pack()
win.mainloop()
In this case the message 'TEST' set through 'set' is not registered in the Label textvariable..
Why does this happen?
Your problem comes from the fact that you have several Tk instances running simultaneously. Tkinter is based on the the Tk gui framework which is a tcl library. Therefore each Tk instance is not just a window, it's also a tcl interpreter, therefore, when you have several Tk instances, they cannot share StrinVar because the value of the StrinVar is defined in one interpreter (here win) which does not communicate with the other one (ven).
To avoid this kind of issue, just don't use several Tk instances, use Toplevel windows instead:
import tkinter as tk
def test():
ven = tk.Toplevel(win)
v1 = tk.StringVar(win)
v1.set('TEST')
print(v1.get())
tk.Label(ven, textvariable=v1).pack()
win = tk.Tk()
tk.Button(text='BOTON', command=test).pack()
win.mainloop()

Asking for user input without input() python 3

for my program i am using tkinter for the GUI. Before the program starts i want to have to input a password. I used the input() function. When running my code in my jupyter notebook everything works fine. So i created and executable file with pyinstaller, but when double clicking it won´t start and ask for the input. Since i often used pyinstaller i don´t think i failed in creating the exe-file, so my guess is, that the problem lies within the input() function. Is there another way to ask for user input?
I tried creating a window with an entry widget via Toplevel but i am not quite sure how to implement it since i want to start the program AFTER i entered the password.
My relevant code:
if __name__=='__main__':
root = tkinter.Tk()
asd = input("Enter the password:")
if asd == str(12345):
app = GUI(master=root)
app.master.title("Programm Links")
app.master.minsize(600,400)
root.config(menu=app.menubar)
app.center(root)
app.mainloop()
else:
root.destroy()
So with help of the comments on my question i got an answer:
import tkinter
from tkinter import messagebox
from tkinter import simpledialog
if __name__=='__main__':
root = tkinter.Tk()
root.withdraw()
asd = tkinter.simpledialog.askstring("Password","Enter the password:")
if asd == str(12345):
app = GUI(master=root)
app.master.title("Programm Links")
app.master.minsize(600,400)
root.config(menu=app.menubar)
app.center(root)
app.mainloop()
else:
messagebox.showwarning("WRONG PASSWORD","You entered a wrong password")
root.destroy()
This creates a dialogbox that asks for a user input. root.withdraw() hides the root window frame that gets created by root = tkinter.Tk() which is needed for the dialogbox to run.

Import an Error class from a package in python

How can I import the Error class (and only the error class, not a namespace) in python to be used in an exception handling?
What's not intended to be used:
from tkinter import _tkinter as tk
try:
...
except tk.TclError:
print('Oops. Bad window path.')
I've tried the above, which works but doing so also imports a bunch of other things into my namespace that I don't need and I also need to use tk.TclError to reference it instead of simply TclError.
What I try to avoid, since it imports the whole package that I do not need, I solely need to handle the exception:
import tkinter as tk
try:
...
except tk.TclError:
print('Oops. Bad window path.')
So how do I import the Error class alone from the package, without getting the whole tkinter namespace, if that's even possible or recommandable?
I have two seperate Programs, I'll call them A and B here to shorten it.
What I would like to achieve
A.py
## Communicator ##
import B
#... Some irrelevant code ...
GUI = B.start()
try:
#Tell the GUI to modify something, for example:
GUI.entry.insert(0, 'Input')
except TclError:
#Modification failed due to Bad Window Path
B.py
## GUI ##
import tkinter as tk
#Little Function to give the Communicator the required object to start/handle the GUI
def start():
root = tk.Tk()
run = Alarmviewer(root)
return run
#... GUI initialization, creating/destroying of windows, modifications, etc
The TclError class can be imported from tkinter. To make it available as tk.TclError just import tkinter with the name tk:
import tkinter as tk
try:
...
except tk.TclError:
...
You can, of course, import just the TclError exception if you wish, though it really doesn't have any actual advantage over importing the entire module in this particular example:
from tkinter import TclError
try:
...
except TclError:
...
Your question claims you must reference it as tk.TclError, but that is a false statement. You reference it by the name you import it as. The name is irrelevant, what is important is the actual exception object itself.
For example, create a file named gui.py, and in that file put this:
# gui.py
import tkinter as tk
def do_something():
raise tk.TclError("something bad happened")
Next, in another file add the following code:
from tkinter import TclError
import gui
try:
gui.do_something()
except TclError:
print("I caught the TclError")
When you run the code, you should see "I caught the TclError" printed.

How to play sounds on python with tkinter

I have been working on a sort of 'Piano' on python. I have used tkinter as the ui,
and this is how it goes:
from tkinter import*
tk =Tk()
btn = Button(tk, text="c note", command = play)
How do I define the function play to play a sound when I press it?
Please Help.
Add these two pieces of code:
from winsound import *
&
command = lambda: Playsound("click_one.wav", SND_FILENAME)
If you don't like lambda then you can define a function before the creation of the button:
def play():
return PlaySound("click_one.wav", SND_FILENAME)
You can also define a lambda function:
play = lambda: PlaySound("click_one.wav", SND_FILENAME)
You can use pygame! It will not create a different window.
Check out Pygame's official site for more amazing functions like getting length.
There are two types of sound you can play sound or even music. Each supports pros and cons.
Tkinter doesn't support audio. You can even use pyglet or other modules.
Example code:
import pygame
from tkinter import *
root = Tk()
pygame.init()
def play():
pygame.mixer.music.load("Musics/example.mp3") #Loading File Into Mixer
pygame.mixer.music.play() #Playing It In The Whole Device
Button(root,text="Play",command=play).pack()
root.mainloop()

Resources