tkinter py script gives different output when called from another script - python

I wrote a script in a .py file that I would like to call from another main file of my program. But when I do that, it does not initialize and give the same output as when runned directly.
here's the code of the main file where I import the subTest file as a module and call it when the user clicks on a button:
#!/usr/bin/python
import tkinter as tk
from tkinter import ttk
import subTest
from subTest import SubTest
class Window(tk.Tk):
def __init__(self, parent):
tk.Tk.__init__(self, parent)
tk.Tk.wm_title(self, "Test")
self.parent = parent
self.initialize()
def initialize(self):
self.geometry("600x300+30+30")
label = tk.Label(self, text="Test")
label.pack(pady=20,padx=10)
self.button = ttk.Button(self, text='gotosubtest', command = self.callsubtest)
self.button.pack()
def callsubtest(self):
app = SubTest(None)
app.mainloop()
if __name__ == "__main__":
window = Window(None)
window.mainloop()
and here's the code of the subTest file containing an Entry text box which should be initialized at 320. This is a simplified example of the problem. when subTest is executed directly, this Entry default value is shown in the text box. But when subTest is called from the main, the value is not shown.
Any idea what's wrong with my code? thanks in advance to all useful tips for a python beginner ;)
#!/usr/bin/python
import tkinter as tk
from tkinter import Entry
class SubTest(tk.Tk):
def __init__(self, parent):
tk.Tk.__init__(self, parent)
tk.Tk.wm_title(self, "SubTest")
self.parent = parent
self.initializesubtest()
def initializesubtest(self):
self.geometry("510x480")
self.minx = tk.DoubleVar()
self.minx.set(320)
Entry(self, textvariable=self.minx,width=5).grid(row=21,column=1)
tk.Label(self, text="Min X").grid(row=22,column=1)
if __name__ == "__main__":
app = SubTest(None)
app.mainloop()

You can only have a single instance of Tk in a program. When you use that other module you are creating a second root window. For you to be able to use that second module in the first, it cannot create its own root window.

Related

tkinter frame has no geometry python tkinter

why do i get this error?
this is my first time trying to understand what is going in a class but i cant seem to figure it out.
the app variable saves it as tkinter windowframe and that way i can put widgets on it but if i need to change the geometry how would i do this?. im sorry for my bad explaining.
Any help would do.
import tkinter as tk
class App(tk.Frame):
def __init__(self, parent):
app = tk.Frame.__init__(self, parent)
self.button = tk.Button(app, text="start")
self.button.pack()
app.geometry("500x400")
if __name__ == "__main__":
app1 = tk.Tk()
App(app1)
app1.mainloop()
When you pass a parameter to class constructor, simply assign it to an instance property (by typing self.instanceProperty = whatYouPassed), then you can work on it.
import tkinter as tk
class App:
def __init__(self, parent):
self.app = parent
self.app.geometry("500x400")
self.button = tk.Button(self.app, text="start")
self.button.pack()
if __name__ == "__main__":
app1 = tk.Tk()
App(app1)
app1.mainloop()
Reading doc about classes might be useful.

How to get a variable out a a tkinter window?

There are some similar questions already on this site. The difference is that I'm coding the Tkinter window as a class. Then making an instance in another file. For example:
import file
gui = file.Window()
gui.mainloop()
# The program continues, using the variables chosen by the user in the previous window.
while file is another file that contains the window code:
import tkinter as tk
class Window(tk.Tk):
def __init__(self, master):
# some code
def mainWidgets(self):
self.body = Body(self)
self.body.grid(row=0, column=0)
class Body(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.master = master
self.widgets()
def widgets(self):
# Labels entries and selections
self.boton_enviar = tk.Button(self, text='Send', command=self.send)
self.boton_enviar.grid()
def send(self):
variables = self.variables
# What code do I add here?
self.quit()
So I want to close the window when clicking the 'Send' button but I need to retrieve some variables to use in the main program. How can I do this ?

Running python script when button is clicked

When I run this Tkinter application, and the submit button is clicked. What should happen is the combobox_window.py should run automatically, and a new Tkinter window should open. However, when do so I get the error:
'combobox_window.py' is not recognized as an internal or external command,
operable program or batch file.
I was using originally using Sublime Text to code, and had no problem with running thecombo_box.py file when the button was clicked. Today I have converted to PyCharm (easier to import libraries), so I am new to it.
Any suggestions?
file1.py
class Completion(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
def next_page():
os.system('combobox_window.py')
submit_button = tk.Button(self, text="Submit", command=next_page)
submit_button.pack()
combobox_window.py
import tkinter as tk
from tkinter import *
class SelectionWindow(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
combobox_values = ("Hello", "Goodbye")
combo = Combobox(state="readonly", values=combobox_values)
combo.pack()
if __name__ == "__main__":
app = SelectionWindow()
app.title("Selection Stage")
app.mainloop()

Tkinter troubles - Name frame is not defined

import Tkinter
class Application(Frame):
def __init__(self, master):
Frame.__init__(self,master)
self.grid()
self.CreateWidgets()
def CreateWidgets(self):
self.LoginButton = Button(Self)
self.LoginButton["text"] = "Login"
self.LoginButton.grid()
self.QUIT_Button = Button(self)
self.QUIT_Button["text"] = "Quit"
self.QUIT_Button["command"] = self.quit
self.QUIT_Button["fg"] = "red"
root = Tk()
root.title("Login")
root.geometry("500x500")
app = Application(root)
root.mainloop()
This is the youtube tutorial that I have been following: https://www.youtube.com/watch?v=YCLTv6wh3jE&index=39&list=PLB0701884E5AE1B45
And this is the error that keeps occurring:
Traceback (most recent call last):
File "C:\Users\omer\Desktop\test.py", line 3, in <module>
class Application(Frame):
NameError: name 'Frame' is not defined
I am a complete noob at Python and am still learning so any help would be appreciated.
Frame Tk, and Button are all located in the Tkinter namespace. Thus, you have to qualify them to let Python know where they are1:
import Tkinter
class Application(Tkinter.Frame):
...
Tkinter.Frame.__init__(self, master)
...
self.LoginButton = Tkinter.Button(self)
...
self.QUIT_Button = Tkinter.Button(self)
...
root = Tkinter.Tk()
That, or you could just import the names directly:
from Tkinter import Frame, Tk, Button
1If you decide to use this first solution, it would probably be best to import Tkinter like this:
import Tkinter as tk
That way, the code becomes this:
import Tkinter as tk
class Application(Tkinter.Frame):
...
tk.Frame.__init__(self, master)
...
self.LoginButton = tk.Button(self)
...
self.QUIT_Button = tk.Button(self)
...
root = tk.Tk()
which is a lot more brief.
You need to import Frame, Button, Tk.
You can either explicitly import all of them from Tkinter:
from Tkinter import Frame, Button, Tk
or import everything from Tkinter (which is not a good thing to do):
from Tkinter import *
or leave your import as is (import Tkinter) and get Frame, Button and Tk from the Tkinter namespace, e.g. for Frame:
class Application(Tkinter.Frame):
Even better would be to import tkinter in a universal way that would work for both python2 and python3:
try:
# Python2
import Tkinter as tk
except ImportError:
# Python3
import tkinter as tk
class Application(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self,master)
self.grid()
self.CreateWidgets()
def CreateWidgets(self):
self.LoginButton = tk.Button(self)
self.LoginButton["text"] = "Login"
self.LoginButton.grid()
self.QUIT_Button = tk.Button(self)
self.QUIT_Button["text"] = "Quit"
self.QUIT_Button["command"] = self.quit
self.QUIT_Button["fg"] = "red"
root = tk.Tk()
root.title("Login")
root.geometry("500x500")
app = Application(root)
root.mainloop()
Also, you have a typo, replace (watch Self):
self.LoginButton = Button(Self)
with:
self.LoginButton = Button(self)
You have to import Frame in order to use it like you are. As it stands you have imported Tkinter, but that doesn't give you access to Frame, Button or Tk the way you've used them. but you either need to do:
from Tkinter import Frame
or
from Tkinter import * (* means 'all' in this case, though this isn't necessary when only using a few modules)
or you could leave your import statement as is(import Tkinter) and change your code like so:
class Application(Tkinter.Frame):
and
self.LoginButton = Tkinter.Button(Self)
However, I would recommend that if you do this, you do:
import Tkinter as tk
That way, you can do tk.Frame and tk.Button etc.
For any modules that you want to use from Tkinter you need to import them also in the same fashion.
You can do single line imports like so:
from Tkinter import Tk, Frame, Button etc.
Check out this info on importing in Python: http://effbot.org/zone/import-confusion.htm
Well it is a bit late but for someone having same error, be sure there is no tkinter.py file in the folder.
I had this same error too. The issue with mine is I had a file called tkinter.py and that was overriding the built-in file tkinter. So to fix it, I changed my filename to something else.

Python tkinter: Make the output appear in a text box on GUI not in the shell

I have a tkinter menu that lets the user choose some functions. I would like if the output of that functions was presented on a texbox in Tkinter instead of the Shell. Im very unexperienced with Tkinter. I donĀ“t have any ideia how to do it..
Some of the functions require inputs of the user, is it possible for the user to input directly from Tkinter Gui?
The code for the menu of the program:
the functions: situacaocorrente(), findfuncionario(), verhistorico() are not presented here.
CODE
from Tkinter import Tk, Frame, Menu, Label, Text
import sys
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.output = Text(self)
self.output.pack()
sys.stdout = self
self.initUI()
def initUI(self):
self.parent.title("High Flex")
menubar = Menu(self.parent)
self.parent.config(menu=menubar)
fileMenu = Menu(menubar)
fileMenu.add_command(label="Procurar funcionario", command=self.procurarfuncionario)
fileMenu.add_command(label="Ver Historico", command=self.historico)
fileMenu.add_command(label="Verificar Onde se encontram os funcionarios", command=self.funcionariosturno)
fileMenu.add_command(label="Sair", command=self.onExit)
menubar.add_cascade(label="INICIAR", menu=fileMenu)
def funcionariosturno(self):
situacaocorrente()
def procurarfuncionario(self):
findfuncionario()
def historico (self):
verhistorico()
def onExit(self):
self.quit()
def write(self, txt):
self.output.insert(END,str(txt))
def main():
root = Tk()
root.geometry("250x150+300+300")
app = Example(root)
root.mainloop()
You can use Entry() to get user input. See more on: An Introduction to Tkinter
I don't know what functions output you try to put in self.output - from external program in shell or from python function.
sys.stdout = self works only with Python functions like print

Categories