How to see code in the console [Python, Tkinter, Atom] - python

I am using Atom to do this, I am asking how to view a variable in the console while also having the TKinter GUI loaded.
My code is as follows:
import random
import tkinter as tk
root = tk.Tk()
rd1 = random.randint(1, 20)
root.mainloop()
Running the program only shows the tk window but I am wondering how I can view the outcome of rd1 from the console, without having to display it in the GUI.
The console becomes a black ver and will only display text when closing the GUI.
Text as follows:
Process returned 0 (0x0) execution time : 1.298 s
Press any key to continue . . .

printing it will show it in the console; sometime it is buffered, so you can add the optional argument flush=True to the print statement.
import random
import tkinter as tk
root = tk.Tk()
rd1 = random.randint(1, 20)
print(rd1, flush=True) # flush will output immediately
root.mainloop()

Related

Always ask for user input while tkinter gui is running in fullscreen mode

My program needs to track the user input at all times. For that i think the input() command is the easiest solution. The problem is: At the same time there should be a Tkinter GUI in fullscreen mode running. I've tried a few things, but nothing really worked out. Here is a simplified program, which shows the problems:
from tkinter import *
import tkinter as tk
from threading import Thread
def GUI():
root=tk.Tk()
Text = Label(master=root, text="Test").pack(side="top")
Button = Button(master=root, text="Button").pack(side="top")
root.mainloop()
def input_loop():
x = input()
print(x)
t1 = Thread(target=GUI)
t2 = Thread(target=input_loop)
t1.start()
t2.start()
Even though now both loops work, i still can't type into the console unless I manually select the console window. Other solutions like the entry widget in tkinter won't work because there is no place for them in my actual program. Please let me know if you find something which works reliably.
i didn't get your problem clearly but i will try to help .
so you are saying the program running on full screen but you want to run it on some resolution?
from tkinter import *
import tkinter as tk
from threading import Thread
def GUI():
root=tk.Tk()
# Program title
root.title("Title")
# Preventing user from fullscreen/resize the window
root.resizable(0, 0)
# Resolution of the windows in pixles
root.geometry(f"{820}x{460}")
Text = Label(master=root, text="Test").pack(side="top")
Btn = Button(master=root, text="Button").pack(side="top")
root.mainloop()
def input_loop():
x = input()
print(x)
t1 = Thread(target=GUI)
t2 = Thread(target=input_loop)
t1.start()
t2.start()
also i changed button function to btn because i faced an error with it , and you can now complete the program and play with the resolution of the buttons and windows so on .

Command execution on closing "X" Tkinter MessageBox

I am trying to restart my main GUI/Halt the program flow when I Click on the "X" button in my tkinter messagebox . Any idea how can I do this ?
PS: I have read the many threads about closing the main GUI itself but nothing specific to messagebox
By default , my code proceeds to ask me for an output path using the filedailog.askdirectory() method when clicking "ok", or on closing the messagebox
My message box and the main GUI in the background
There's no simple way to add a custom handler to the "X" button. I think it's better to use messagebox.askokcancel() variation of messageboxes instead of showinfo, and halt the program if the returned result is False:
import tkinter as tk
from tkinter import messagebox, filedialog
root = tk.Tk()
def show_messagebox():
result = messagebox.askokcancel("Output path", "Please select an output file path")
if result:
filedialog.askdirectory()
else:
messagebox.showinfo("Program is halted")
tk.Button(root, text="Show messagebox", command=show_messagebox).pack()
root.mainloop()
Or, even simpler, you can just show filedialog.askdirectory() directly. If the user doesn't want to choose directory, they can click on the "Cancel" button, and then the program checks if there was empty value returned, and halts if so:
import tkinter as tk
from tkinter import messagebox, filedialog
root = tk.Tk()
def show_askdirectory():
directory = filedialog.askdirectory(title="Please select an output file path")
if not directory:
messagebox.showinfo(message="The program is halted")
else:
messagebox.showinfo(message="Chosen directory: " + directory)
tk.Button(root, text="Choose directory", command=show_askdirectory).pack()
root.mainloop()

Error with TKinter Attribute Simpledialog

I'm currently trying to write in a few basic user input boxes using the tkinter module in Python 3.6 (via Spyder). I can confirm that the module loads, and that the option to select simpledialog comes up, but I keep getting the following error:
AttributeError: module 'tkinter' has no attribute 'simpledialog'
Image of tkinter simpledialog
I've tried to look for other options, but other user input options do not seem to work on my Python interface. It either crashes, or the data isn't structured properly.
Interestingly enough, in the past, I've done similar things in Python with no errors, but this keeps coming up with this particular programming piece.
import tkinter as tk
import pyodbc as py
py.pooling = False
## INPUT YOUR USER ID AND PASSWORD AND DECLARE YOUR CONNECTION
## THE DIALOG BOXES MAY POP OPEN ON ANOTHER SCREEN
## THE PASSWORD INPUT IS MASKED AND WILL NOT SHOW IN THE
## VARIABLE EXPLORER
ID = tk.simpledialog.askstring("Please input your username.","Username: ")
PW = tk.simpledialog.askstring("Please input your password.",
"Password: ", show='*')
CONN = tk.simpledialog.askstring("Please input your connection.",
"Connection: ")
My expected results are that a popup window will appear and that I'll be able to get the user information I need to maintain a stable connection to the server I'm using.
Thank you in advance for your advice!
simpledialog is not in tkinter but in tkinter.simpledialog and you have to import it
import tkinter as tk
import tkinter.simpledialog
root = tk.Tk() # create main window
#root.iconify() # minimize main window
root.withdraw() # hide main window
answer = tkinter.simpledialog.askstring("Question", 'Your name:')
print(answer)
#root.destroy() # should work without it
#root.mainloop() # should work without it
See tkinter modules
import tkinter as tk
from tkinter import simpledialog
root = tk.Tk()
ID = simpledialog.askstring("Please input your username.", "Username: ", parent=root)
root.mainloop()
This will keep the popup within the parent window and visible.

Tkinter Text closes but ipython console keeps running indefinetly

I am trying to print some rows of a pandas dataframe for the user of my tkinter GUI. However, in this test, the tk window is showed, but when closed, the code stop running.
import pandas as pd
import numpy as np
import sys
from tkinter import *
dates = pd.date_range('20160101', periods=6)
df = pd.DataFrame(np.random.randn(6,4),index=dates,columns=list('ABCD'))
root = Tk()
t1 = Text(root)
t1.pack()
class PrintToT1(object):
def write(self, s):
t1.insert(END, s)
sys.stdout = PrintToT1()
print ('Hello, world!')
print (df)
mainloop()
root.destroy()
print(2)
I am running the script in Spyder, and when I close the window, the ipython console continues processing something, but it never reaches the last line to print the number 2, and I have to restart the console manually.
I want it to close the tk window and continues the script, since in the GUI, after closing the tk window, the code will have to do some calculations for the user. How could I do this?
picture
I am new here (page) but the error is that the mainloop is a loop itself If you close the window the program closes.
root_window.mainloop()
#destroy()use in ithems or daughters windows
test add:
def date_name(self):
t3 = Toplevel(root)
t3.geometry('240x100+20+20')
t3.title("...")
t3.destroy()#use valid
The sample of the data in that window and the function destroy ().
Find how to use the Canvas and the Frame if you want to request the data from the same window but the fields of texts and buttons belong to the cambas ... well I work like that in tkinter.
canvas_menu = Canvas(root, width=200, height=200)
canvas_menu.destroy()#this use valid
root.destroy not valid Tk()is a funcion.
test:
from tkinter import *
from tkinter import ttk
root=Tk()
def new_window():
t3 = Toplevel(root)
t3.geometry('240x100+20+20')
t3.title("...")
Label(t3,text="I hope to help you").pack()
Button(t3,text="destroy() in t3 ",command=t3.destroy).pack()
canvas_c=Canvas(root, width=400, height=400)
canvas_c.pack()
canvas_c.config(bg="blue")
Label(canvas_c,text="info").place(x=100,y=250)
ba=Button(root,text="new_window",command=new_window).pack()
bb=Button(root,text="destroy() in canvas",command=canvas_c.destroy).pack()
root.mainloop()
and run run.jpg

python button combination to open a tkinter message box

im new topython 2.7 and want to know if it is possible to open a tkinter messagebox with a button combination on keyboard (Ctrl+alt+'something')
that pops up like an windows error message
import win32api
import time
import math
import Tkinter
import tkMessageBox
top = Tkinter.Tk()
def Message():
tkMessageBox.showinfo("Window", "Text")
for i in range(9000):
x = int(600+math.sin(math.pi*i/100)*500)
y = int(500+math.cos(i)*100)
win32api.SetCursorPos((x,y))
time.sleep(.01)
Yes, you can bind to control and alt characters. Bindings are fairly well documented. Here's one good source of information:
http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm
As an example, to bind to ctrl-alt-x you would do this:
top.bind("<Control-Alt-x>", Message)
You can bind to a sequence of events by specifying the whole sequence. For example, if you wanted to implement a cheat code you could do something like this:
label.bind("<c><h><e><a><t>", Message)
For letters, "a" is the same as "<a>", so you can also do this:
label.bind("cheat", Message)
Here is a complete working example:
import Tkinter as tk
import tkMessageBox
def Message(event=None):
tkMessageBox.showinfo("Window", "Text")
def Cheat(event=None):
tkMessageBox.showinfo("Window", "Cheat Enabled!")
root = tk.Tk()
label = tk.Label(root, text="Press control-alt-m to see the messagebox\ntype 'cheat' to enable cheat.")
label.pack(fill="both", expand=True, padx=10, pady=100)
label.bind("<Control-Alt-x>", Message)
label.bind("<c><h><e><a><t>", Cheat)
label.focus_set()
root.mainloop()
If you want something like: Press button A, then press button B then open a Message box it is possible.
Do something like:
from Tkinter import *
import tkMessageBox
def change():
global switch
switch=True
def new_window():
if switch:
tkMessageBox.showinfo("Random name", "Correct combination")
else:
print "Not the correct order"
root = Tk()
switch = False
root.bind("<A>", change)
root.bind("<B>",new_window)
root.mainloop()
If you want more buttons then use an integer and increase it while using switches for the correct button order.
Note that you can bind key combinations as well with root.bind("<Shift-E>") for example
Edit: Now a and b keyboard button insted of tkinter buttons

Categories