Not Displaying the Keyboard Inputs as Labels in the Window in Python - python

How can I display the letters entered from the keyboard as labels in the gui window?
I can only view it on the console right now.
from tkinter import*
from tkinter import ttk
window = Tk()
def letter(event):
a=str(print (repr(event.char)," key pressed."))
label=Label(window,text=a)
label.place(x=15,y=15)
def clicked(event):
frame.focus_set()
print(event.x,event.y ,"coordinate clicked.")
frame =Frame(window, width=500, height=500)
frame.bind("<Key>",letter)
frame.bind("<Button-1>", clicked)
frame.pack()
window.mainloop()

I see a few problems with your code.
What do you think str(print (repr(event.char)," key pressed.")) returns? It returns a None value which is then put into the label and the label is showing "None".
In the function letter you are creating a Label every time the function is called, which means it is just overlapping the label on a label created before. So create one label outside the function and then update that label into that function.
Complete code:
from tkinter import*
from tkinter import ttk
window = Tk()
def letter(event):
a = "'%s' key pressed" %event.char
print(a)
# Update the text of label.
label['text'] = a
def clicked(event):
frame.focus_set()
print(event.x,event.y ,"coordinate clicked.")
frame =Frame(window, width=500, height=500)
frame.bind("<Key>",letter)
frame.bind("<Button-1>", clicked)
frame.pack()
label=Label(window, text='Key')
label.place(x=15, y=15)
window.mainloop()

Related

How to open the initial window in tkinter again?

I have a following question. I want to make a button in tkinter that will delete existing changes and the window will looks like the initial window.
This is my initial Window 1:
This is how the window looks like when I click on the first two buttons, Window 2:
Now I would like to click on the "Zpět" button and I want to see Window 1 again.
Here is my code:
import tkinter as tk
root = tk.Tk()
home_frame = tk.Frame(root)
home_frame.grid(row=0, column=0, sticky="news")
def raise_new_payment():
tk.Label(text=f"Stav bilance k 2021-09-09").grid()
def back():
"""I would like to this function to clean everything."""
tk.Label().destroy()
platba = tk.Button(
home_frame,
text="Zadej novou platbu",
command=lambda: raise_new_payment(),
)
platba.pack(pady=10)
zpet = tk.Button(
home_frame,
text="Zpět",
command=back,
)
zpet.pack(pady=10)
I don't know how to use the back() function. I tried to delete the tk.Label as created in raise_new_payment(), but it did not work. Can you help me please? Thanks a lot.
I would suggest you create the label once and don't call .pack() on it first, i.e. it is not visible initially.
Then update it inside raise_new_payment() and call .pack() to show it.
You can call .pack_forget() to hide it again inside back().
import tkinter as tk
root = tk.Tk()
home_frame = tk.Frame(root)
home_frame.grid(row=0, column=0, sticky="news")
def raise_new_payment():
# update label and show it
lbl.config(text=f"Stav bilance k 2021-09-09")
lbl.pack()
def back():
# hide the label
lbl.pack_forget()
platba = tk.Button(
home_frame,
text="Zadej novou platbu",
command=lambda: raise_new_payment(),
)
platba.pack(pady=10)
zpet = tk.Button(
home_frame,
text="Zpět",
command=back,
)
zpet.pack(pady=10)
# create the label and initially hide it
lbl = tk.Label(home_frame)
root.mainloop()

How to create a new Tkinter window frame within a window?

So basically I am making a GUI with Tkinter. I also want to make a frame within the Tkinter window, and it should open when I click a button.
Here is my code so far:
from tkinter import *
import tkinter
screen = Tk()
screen.title("My GUI")
screen.geometry("600x600")
screen.configure(background="Gray")
button1 = Button(screen)
button.pack()
screen.mainloop
So how do I make a new window(frame) when I click the button?
You can create/toggle frame following the below logic
from tkinter import *
import tkinter
screen = Tk()
screen.title("My GUI")
screen.geometry("600x600")
screen.configure(background="Gray")
frame_enabled = False
def toggle_frame():
global frame_enabled
if not frame_enabled:
my_frame.pack(fill='both', expand=True)
else:
my_frame.pack_forget()
frame_enabled = not frame_enabled
button1 = Button(screen, text="Toggle frame", command=toggle_frame)
button1.pack()
my_frame = Frame(screen, bg="red")
screen.mainloop()

How to make a Label appear then disappear after a certain amount of time in python tkinter

I would like for a cant afford label to appear then after a second disappear when i push a button to buy something. It seems like the time.sleep(1) is making it not work properly. This is done on python tkinter.
def buttonpressed():
Label.place(x = 500, y = 500 #where i want the label to appear
time.sleep(1)
Label.place(x = 10000, y = 10000) #moving it away where i wont be able to see it
You can't use sleep because it stops mainloop
You can use root.after(time_in_milliseconds, function_name) to run function
Example
import tkinter as tk
def button_pressed():
# put text
label['text'] = "Hello World!"
# run clear_label after 2000ms (2s)
root.after(2000, clear_label)
def clear_label():
# remove text
label['text'] = ""
root = tk.Tk()
label = tk.Label(root) # empty label for text
label.pack()
button = tk.Button(root, text="Press Button", command=button_pressed)
button.pack()
root.mainloop()
If you have to create and remove label then use label.destroy()
import tkinter as tk
def button_pressed():
label = tk.Label(root, text="Hello World!")
label.pack()
root.after(2000, destroy_widget, label) # label as argument for destroy_widget
def destroy_widget(widget):
widget.destroy()
root = tk.Tk()
button = tk.Button(root, text="Press Button", command=button_pressed)
button.pack()
root.mainloop()
And shorter version without destroy_widget
import tkinter as tk
def button_pressed():
label = tk.Label(root, text="Hello World!")
label.pack()
root.after(2000, label.destroy)
root = tk.Tk()
button = tk.Button(root, text="Press Button", command=button_pressed)
button.pack()
root.mainloop()
Press button many times to see many labels which disappear after 2s.
You can use after() to set up a callback after a specified interval. In the callback function clear the label with pack_forget() (or grid_forget() if you're using grid). This is better than setting the label's text attribute to an empty string because that causes widgets to be resized, which might not be what you want. Here's an example:
import Tkinter as tk
class App():
def __init__(self):
self.root = tk.Tk()
self.label = tk.Label(text='I am a label')
self.label.place(x=0, y=0)
self.label.after(1000, self.clear_label) # 1000ms
self.root.mainloop()
def clear_label(self):
print "clear_label"
self.label.place_forget()
app=App()
Another option is to use self.label.destroy() to destroy the widget, however, pack_forget() allows you to display the label again by calling pack() on the widget again.
# I made it through calling 2 functions:
from tkinter import *
root = Tk()
root.geometry('400x200') # width by height
def one_text():
label['text'] = "Look around"
root.after(1000, another_text)
def another_text():
label['text'] = "and smile"
root.after(1000, one_text)
label= Label(root ,font=('Helvetica', 14), fg='black', bg='white')
label.pack()
one_text()
root.mainloop()

tkinter canvas image is not displayed in class

I am trying to display an image in python using the tkinter canvas option. However, if I input it in a class, like below, it doesn't give an error but also doesn't show my image. The buttons are displayed correctly though. Also, if I take the code for generating this image out of the class it works correctly. I can't seem to find out what the problem is.
import Tkinter as tk
from Tkinter import *
class Board(tk.Frame):
def __init__(self,parent):
frame = Frame(parent)
frame.pack()
tk.Frame.__init__(self,parent)
frame2 = Frame(frame)
frame2.pack()
c=Canvas(frame2)
c.pack(expand=YES,fill=BOTH)
background=PhotoImage(file='Board.gif')
c.create_image(100,100,image=background,anchor='nw')
button = Button(frame, text="Next turn", command=self.next_turn)
button.pack()
button = Button(frame, text="Roll the dice", command=self.roll)
button.pack()
....
root = Tk()
board = Board(root)
board.pack()
root.mainloop()
You have to keep a reference to the PhotoImage. This is just and example (you can also use self.background instead of c.background):
c = Canvas(frame2)
c.pack(expand=YES,fill=BOTH)
c.background = PhotoImage(file='Board.gif')
c.create_image(100,100,image=c.background,anchor='nw')

Tkinter Scrollbar in frame with multiple textframes

Question
How can I have a scrollbar which moves an entire Tkinter frame? Note: I am using Python 2.7.3.
Code and Explanation
I have this code for defining the scrollbar
scrollbar = Scrollbar(soeg)
scrollbar.pack(side=RIGHT, fill="y")
And this code for defining the textframes
h = 0
s = 0
for i in dom_nodup:
abc = dom_nodup[h]
text = Text(soeg, bg="brown", fg="white", height="10", width="60")
text.insert(INSERT, "%s \n" % abc[0])
text.insert(END, "%s \n\n\n" % abc[1])
text.pack()
h += 1
s += 1
A new textframe is created for each text entity for later easier overview (planning on having a button to show/hide the input).
The scrollbar is present but is not functional
I would recommend that you use the ScrolledText widget. It automatically adds a scrollbar to each text widget, and has the same arguments as Text. Here is a brief example of how to do it.
from Tkinter import * #Import the Tkinter module
from ScrolledText import ScrolledText #import the scrolled text module
message = "I \n am \n scroll \n able. \n\n\n\n\n\n Yes I am!"
class Application(Frame): #Create a frame for the widgets
def __init__(self, master): #initialize the grid and widgets
Frame.__init__(self,master)
self.grid()
self.widgets()
def widgets(self):
self.mytext = ScrolledText(self, width = 10) #Creates the widget
self.mytext.grid() #Places it
root = Tk()
root.title("My Text Example")
#make my screen dimensions work
root.geometry("500x1000")
app = Application(root)
root.mainloop()
For more information, please see the Tkinterbook and this question.
To make a scrollbar functional you must do two things: you must tell it which scrollable widget to scroll, and you must tell the scrollable widget which scrollbar to update with the current position.
scrollbar.configure(command=text.yview)
text.configure(yscrollcommand=scrollbar.set)

Categories

Resources