How to cal tcl commands inside my python script using tkinter? - python

I am running my performance test on python and I want to call some Tcl commands using Tkinter inside my python script.
Can somebody please help me to write the code,
import Tkinter
root = Tkinter.Tk()
root.tk.eval('puts {printed by tcl}')
I tried simply above example, here when I do root=tkinter.tk() it opens up a window, I just want to execute my command and get the result

The code you have tried will not show any window until you put the root.mainloop(),but you can try something like this,
import tkinter
root = tkinter.Tk()
root.withdraw()
root.tk.eval('puts {printed by tcl}')
root.destroy()
root.mainloop()
here withdraw() will remove the window from the screen without destroying it and then you can perform your tasks and then destroy it at the end of code.

Related

How do I execute a code within a tk.Toplevel()

I'm somewhat new to python (started in Nov.) and after complete my first "program" I'm trying to built the GUI using Tkinter. I want to put the program on a Toplevel that I've created and have it run, but all Tkinter tutorials only talk about widgets and I don't know how to specify that a code should run on a specific Toplevel window. The best I can figure is to run the in the section where I define the Toplevel as shown in the example below, but that is not working.
from tkinter import *
import tkinter as tk
root=Tk()
root.geometry("500x200")
root.title('Test')
Label(root, text="Test").pack()
def test():
gen_win = Toplevel(root)
gen_win.title("Test")
gen_win.geometry("500x500")
Label(gen_win, text="Test").pack()
print(2+2)
btn_test=tk.Button(root, text="test", command=test).pack(fill=tk.X)
root.mainloop()
The example program (print(2+2)) doesn't print on the toplevel. Any ideas?
#jasonharper gave the correct answer:
"Code doesn't "run on a specific Toplevel window". It just runs, and if it happens to create a widget, or modify the contents of an existing widget, that change becomes visible as soon as your code returns to the mainloop. Label(gen_win, text=str(2+2)).pack() would be the simplest way to make your addition results visible in the window."

What kind of code does tkinter's mainloop collect?

Suppose I have Python code like this
# <Pure Python statement A>
root = tk.Tk()
mainframe = tk.Frame(root)
# <Pure Python statement B>
# <other tkinter code>
root.mainloop()
Which statements are then ending up on tkinter's mainloop? Is it just the 3 tkinter statements?
EDIT
There must be more things going on, because some code between the tkinter code is affected: When I run the following code (taken from another question)
import tkinter as tk
import tkinter.filedialog
filename = ""
def op():
global filename
filename =tk.filedialog.askopenfilename()
root = tk.Tk()
mainframe = tk.Frame(root)
mainframe.grid(column=0, row=0)
tk.Button(mainframe, text="Open file", command=op).grid(column=0, row=1)
root.mainloop()
print(filename)
after closing the program the selected filename is displayed. But when running
import tkinter as tk
import tkinter.filedialog
filename = "this_is_a_test"
def op():
global filename
filename =tk.filedialog.askopenfilename()
root = tk.Tk()
mainframe = tk.Frame(root)
mainframe.grid(column=0, row=0)
tk.Button(mainframe, text="Open file", command=op).grid(column=0, row=1)
print(filename)
root.mainloop()
after closing the program, nothing is displayed. So somehow the pure Python statements before mainloop seem to get absorbed.
What kind of code does tkinter's mainloop collect?
It doesn't collect anything. It simply processes events, and calls functions bound to those events. It also calls functions added to the queue via after.
Which statements are then ending up on tkinter's mainloop? Is it just the 3 tkinter statements?
Nothing "ends up on tkinter's mainloop". That's a nonsensical statement, nothing can end up on it. It is just a function that processes events, and doesn't return until the window is destroyed. All code before the call to mainloop executes according to the normal rules of python.
Calling mainloop is effectively the same as if you put this in its place (but it is much more efficient):
while True:
self.update()
Much like with the above, any code after mainloop() will not execute until the loop exits, which happens when the window has been destroyed.
The reason your print seems to work after the call to mainloop but not before is simply that before mainloop, filename is the empty string. The print run normally, it's just that there's nothing to print. That print statement happens a few milliseconds after the program starts, way before the user has a chance to do anything. When called after, it seems to work because that code doesn't run until the window has been destroyed. At that point it presumably has a value, so you see something printed.
The simple answer is: There's no kind of code that mainloop collects.
It 'collect' s all configuration that is related to the Tcl interpreter it is a method of. As in if your GUI is a configuration of root = tk.Tk(), and the mainloop is a method of root then all configurations under it will be accounted for such as children widgets and their configurations.
Your print statement doesn't get absorbed. It simply prints what would've been printed if the button was never used. Try the 2nd code with simply closing the GUI without using the button. mainloop doesn't absorb anything. It simply waits for events for the GUI configured.

Python: How to close the previous Main (top) tkinter windows

I want my script should work in such a way that, close all the previous windows in tkinter.
If I minimise the existing pop up window and again I will run same script, it will again pop up new window. How can I close the already existing window, when i run script again?
Simple code:
import Tkinter as tk
root = tk.Tk()
root.mainloop()
Maybe if you check all variable in locals and see if you have tk type in it?
import tkinter as tk
root = tk.Tk()
tk_type = type(root)
print(tk_type)
var=0
for var in locals().items():
if type(var[1]) == tk_type:
print(var, 'to be deleted')
root.mainloop()
something like this where you can put the test at the begining of the class to see if it exists other TK window object.
I'm sure it should exist a better solution though.

How to use idlelib.PyShell to embed an interpreter in a tkinter program?

I need to embed an interative python interpreter into my tkinter program. Could anyone help me out as to how to integrate it?
I have already looked at the main() function, but it's way to complex for my needs, but I can't seem to reduce it without breaking it.
Some details of what you must do may depend on what you want to do with IDLE's Shell once you have it running. I would like to know more about that. But let us start simple and make the minimum changes to pyshell.main needed to make it run with other code.
Note that in 3.6, which I use below, PyShell.py is renamed pyshell.py. Also note that everything here amounts to using IDLE's private internals and is 'use at your own risk'.
I presume you want to run Shell in the same process (and thread) as your tkinter code. Change the signature to
def main(tkroot=None):
Change root creation (find # setup root) to
if not tkroot:
root = Tk(className="Idle")
root.withdraw()
else:
root = tkroot
In current 3.6, there are a couple more lines to be indented under if not tkroot:
if use_subprocess and not testing:
NoDefaultRoot()
Guard mainloop and destroy (at the end) with
if not tkroot:
while flist.inversedict: # keep IDLE running while files are open.
root.mainloop()
root.destroy()
# else leave mainloop and destroy to caller of main
The above adds 'dependency injection' of a root window to the function. I might add it in 3.6 to make testing (an example of 'other code') easier.
The follow tkinter program now runs, displaying the both the root window and an IDLE shell.
from tkinter import *
from idlelib import pyshell
root = Tk()
Label(root, text='Root id is '+str(id(root))).pack()
root.update()
def later():
pyshell.main(tkroot=root)
Label(root, text='Use_subprocess = '+str(pyshell.use_subprocess)).pack()
root.after(0, later)
root.mainloop()
You should be able to call pyshell.main whenever you want.

Python Tkinter not working in a .py file

My problem is that my python code is not working when I run it as a .py file. Here is the code:
import tkinter
tk=tkinter.Tk()
canvas=tkinter.Canvas(tk, width=500, height=500)
canvas.pack()
There is more code to it than that, but that is the relevant stuff. It works fine when I use the python shell or type it directly into the python console, but when I run it as a .py file, it seems to skip this code and go on to the rest, without displaying a canvas. I am using windows, but I am not sure what version of python I'm using.
I was also using
from * import tkinter
before, with relevant changes to the code and i changed it to try and help fix it. It didn't work :(
You are missing the eventloop at the end:
import tkinter
tk=tkinter.Tk()
canvas=tkinter.Canvas(tk, width=500, height=500)
canvas.pack()
# Enter into eventloop <- this will keep
# running your application, until you exit
tk.mainloop()
Only a personal recommendation: don't use tk as a variable name, use app or root or even win/window

Categories

Resources