Using Tkinter in Python I am trying to change what is displayed in a textbox when a button is pressed. My code so far is:
screen = Tk()
text = Text(screen, height = 2, width = 30)
text.pack()
text.insert(END, '-')
def apress():
text.insert(END, 'a')
a = Tkinter.Button (screen, text = 'a', width = 5, command = apress).pack()
mainloop()
When the code is run nothing happens and the debugger will not stop running even if you click 'abort debugging'. Is there a way to fix this?
Here's the working code:
from Tkinter import *
screen = Tk()
text = Text(screen, height = 2, width = 30)
text.pack()
text.insert(END, '-')
def apress():
text.insert(END, 'a')
btn = Button(screen, text = 'a', width = 5, command = apress)
btn.pack()
mainloop()
Changes I made:
Added the import from Tkinter import *
Used Button instead of Tkinter.Button - since we used an wildcard import
Button.pack() separated on a new line
Demo:
Initial view:
Clicked the button several times:
Related
I was able so successfully place the input module earlier but now when I try to implement code to use 'Enter' to accept the input I'm not even able to get it to pack. If anyone can help me it would be thoroughly appreciated. Eventually I am trying to make it so that whatever typed ends up being incrementally placed as a title in a column centered to the left of the entry widget but I will work on that later. (this is the UI for a text adventure game)
Below is the code I have so far
#imports
import time, os, sys, logging
from pynput import *
from tkinter import Button
from tkinter import *
import customtkinter
import tkinter.font as font
from tkinter import simpledialog
import tkinter
import time
import tkinter as tk
userin = ''
#graphics
the_path_text = '''
┏┓┏┓╋╋╋╋╋╋╋╋┏┓┏┓
┃┗┫┗┳━┓┏━┳━┓┃┗┫┗┓
┃┏┫┃┃┻┫┃╋┃╋┗┫┏┫┃┃
┗━┻┻┻━┛┃┏┻━━┻━┻┻┛
╋╋╋╋╋╋╋┗┛'''
#window
customtkinter.set_appearance_mode("dark")
customtkinter.set_default_color_theme("dark-blue")
root = customtkinter.CTk()
root.geometry("800x520")
root.resizable(width = False, height = False)
root.title('The Path')
photo = PhotoImage(file = "D:\\pathpic.png")
root.iconphoto(False, photo)
myfont = ("Roboto Mono",30)
frame = customtkinter.CTkFrame(master = root)
frame.pack(pady = 20, padx = 60, fill = 'both', expand = True)
#splash/start screen
#loading
label = customtkinter.CTkLabel(root, text="Loading", font= ('Roboto', 20))
label.pack()
# Incrementally add dots
for i in range(3):
label.configure(text="Loading" + "." * (i + 1))
time.sleep(.5)
root.update()
# Clear the label text
label.configure(text="")
# Incrementally add dots again
for i in range(3):
label.configure(text="Loading" + "." * (i + 1))
time.sleep(.5)
root.update()
label.configure(text=" ")
#splash logo
label_path_logo = customtkinter.CTkLabel(master=frame, text= the_path_text, font = ('Roboto', 20))
label_path_logo.pack(pady =12, padx = 10)
#clearing splash/ main game loop
start = 0
def clear_start():
time.sleep(.2)
global frame, root
frame.destroy()
frame = Frame(root)
frame.pack()
start_button.destroy()
start = 1
#main game
start_button = customtkinter.CTkButton(master=root, text="Enter the path", command = clear_start)
start_button.pack(padx = 6, pady=20)
while start == 1:
#main text console
main_entry = root.entry = customtkinter.CTkEntry(root, textvariable=userin, placeholder_text="Enter Command")
main_entry.pack(side = BOTTOM,fill = BOTH, pady = 5, padx = 200 )
def process(event=None):
content = main_entry.get() # get the contents of the entry widget
print(content) # for example
main_entry.bind('<Return>', process)
root.mainloop()
When I watched ecnerwala videos on competitive programming, I found something interesting in his video.
This running text
ecnerwala running text
Here is the link of the video
https://www.youtube.com/watch?v=ExmrrXi04vI&t=1030s
So I tried to create something like that running text using tkinter.text widget in python.
I create a window, add text object to it, and bind all keyboard keys to the window. I insert those keys into the text object when any key is pressed. I also make sure that even if I press the enter button, I don't insert it as a newline to the text widget but as the word 'Return' instead
Of course, there is a possibility that the length of all characters I insert into the text is longer than the length of the text widget could fit in one sentence. That's why I want to make the text widget to "always" see the characters from index END-(the number of character the widget could fit) until END
Here is my code
from tkinter import *
def handle(event):
text.config(state = NORMAL)
text.insert(END, event.keysym)
text.config(state = DISABLED)
# Things to be fix
text.doSomethingToMakeItBehaveLikeEntryWidget()
window = Tk()
window.geometry('500x500')
text = Text(window, font = ('Arial', 20), height = 1)
entry = Entry(window, font = ('Arial', 20))
text.config(state = DISABLED)
text.pack()
entry.pack()
window.bind('<Key>', handle)
window.mainloop()
Is there any solution for this problem? Even if I have to use another widget instead of text widget to solve it? Thanks for the help
Given that you use only one line in the text widget, you can use an entry in read-only mode instead.
No matter whether you use an entry or a text widget, you can use the method text.xview_moveto(<fraction>) to set which part of the content is visible, <fraction> being the relative portion of the widget's content which is hidden on the left. If you set this fraction to 1, it will ensure that the last character is visible.
from tkinter import *
def handle(event):
text.config(state=NORMAL)
text.insert(END, event.keysym)
text.config(state="readonly")
text.xview_moveto(1)
window = Tk()
window.geometry('500x500')
text = Entry(window, font = ('Arial', 20), state="readonly", readonlybackground="white")
entry = Entry(window, font = ('Arial', 20))
text.config(state = DISABLED)
text.pack()
entry.pack()
window.bind('<Key>', handle)
window.mainloop()
Try this.
from tkinter import *
from tkinter.scrolledtext import ScrolledText
def handle(event):
text.config(state = NORMAL)
text.insert(END, event.keysym)
text.config(state = DISABLED)
t = text.get('1.0','end-1c')
length= len(t)
width =text.winfo_width()
max_char = int((35/500)*width)
if max_char < length:
a = length-max_char
text.config(state = NORMAL)
text.delete(1.0,END)
text.insert(1.0,t[a:])
text.config(state = DISABLED)
window = Tk()
window.geometry('500x500')
text = Text(window, font = ('Arial', 20), height = 1)
entry = Entry(window, font = ('Arial', 20))
text.config(state = DISABLED)
text.pack()
entry.pack()
window.bind('<Key>', handle)
window.mainloop()
Okay so what I'm trying to figure out is how to control the location of output.
Currently when you run the code a window comes up and allows you to type into a label "manual". with the option to press enter or click the 'submit' button. The typed entry is then put in a new pop-up window every time I.e. Input1(test) and input2(testing) will show up in separate windows. How do I set it so it shows up in the same pop-up window preferably spaced on the y axis so it isn't cluttered. As this is a manual entry there is no telling how many entries will be submitted and it may be possible once so many entries have been entered it will need to move over on the X axis and start again at the top of the Y axis.
I'd also like to know how to pick where the pop-up ends up on the screen I tried using
win.place(x=200, y=50) but the .Toplevel() doesn't have an attribute of .place()
import tkinter as tk
#function that prints the entry
def entry_function(e=None):
name = entry.get()
win = tk.Toplevel()
tk.Label(win, text=name).pack()
win.geometry('100x100')
#Setup for the window
window = tk.Tk()
window.title("Title_Name")
window.geometry("500x500")
window.bind('<Return>', entry_function)
#widgets
label = tk.Label(window, text = "Manual:", bg = "dark grey", fg = "white")
entry = tk.Entry()
button = tk.Button(text = "submit",
command = entry_function)
#widget placement
label.place(x=0,y=20)
entry.place(x=52,y=21)
button.place(x=177, y=18)
window.mainloop()
For displaying the entry on same popup, you can use the below code for entry function
import tkinter as tk
flag = False
win=""
def setflag(event):
global flag
flag = False
#function that prints the entry
def entry_function(e=None):
global flag,win
name = entry.get()
if not flag:
win = tk.Toplevel()
win.geometry('100x100')
win.bind('<Destroy>', setflag)
tk.Label(win, text=name).pack()
flag = True
win.geometry("+%d+%d" % (x + 200, y + 50))
else:
tk.Label(win, text=name).pack()
#Setup for the window
window = tk.Tk()
window.title("Title_Name")
window.geometry("500x500")
window.bind('<Return>', entry_function)
x = window.winfo_x()
y = window.winfo_y()
sh = window.winfo_screenheight()
sw = window.winfo_screenwidth()
x_cord = int((sw/2)-550)
y_cord = int((sh/2)-300)
wh = 550
ww = 1100
window.geometry("{}x{}+{}+{}".format(ww, wh, x_cord, y_cord))
#widgets
label = tk.Label(window, text = "Manual:", bg = "dark grey", fg = "white")
entry = tk.Entry(window)
button = tk.Button(window,text = "submit",
command = entry_function)
#widget placement
label.place(x=0,y=20)
entry.place(x=52,y=21)
button.place(x=177, y=18)
window.mainloop()
You need to create the popup once and add label to it inside entry_function().
You can make the popup hidden initially and show it inside entry_function() and you can specify the position of the popup using geometry().
def entry_function(e=None):
MAX_ROWS = 20 # adjust this value to suit your case
name = entry.get().strip()
if name:
n = len(popup.winfo_children())
tk.Label(popup, text=name).grid(row=n%MAX_ROWS, column=n//MAX_ROWS, sticky='nsew', ipadx=2, ipady=2)
popup.deiconify() # show the popup
window.focus_force() # give focus back to main window
...
# create the popup
popup = tk.Toplevel()
popup.withdraw() # hidden initially
popup.geometry('+100+100') # place the popup to where ever you want
popup.title("Log Window")
popup.protocol('WM_DELETE_WINDOW', popup.withdraw) # hide popup instead of destroying it
...
I am trying to make a very simple GUI with tkinter to operate my python script and what I want to do is to read image files from a folder using a button and after that I want to name this image like "image1" to use in my functions. In my script I have decide() and convert to grayscale() functions which take image as input and make something. How can I proceed this algorithm? my GUI script is that I wrote up to now is below.
I created 4 buttons. "import image" is to select image file from the folder. "decide" button needs decide(image) argument and I dont know how can I combine these.
from tkinter import *
from PIL import Image, ImageTk
from tkinter import ttk
from tkinter import filedialog
window = Tk()
window.title("Welcome to LikeGeeks app")
window.geometry('350x200')
def close_window():
window.destroy()
def open_image():
pil_image = Image.open(filedialog.askopenfilename())
#in btn1 when I click button a folder is opening and I can chose image file, but I cant do anything that I explaned above.
btn1 = Button(window, text="Import Image")
btn1.config( height = 2, width = 15,command=open_image)
btn1.grid(column=0, row=0)
btn2 = Button(window, background = 'white', foreground = 'black', text="exit")
btn2.config( height = 2, width = 15, command = close_window)
btn2.grid(column=0, row=3)
btn3 = Button(window, text=" decide")
btn3.config( height = 2, width = 15 , command = quit)
btn3.grid(column=0, row=2)
btn4 = Button(window, text=" convert gray scale")
btn4.config( height = 2, width = 15 )
btn4.grid(column=0, row=1)
window.mainloop()
My program has a library which opens a new window
This is the library (its called make_entry):
from tkinter import *
def Create():
Window = Tk() # window
Window.geometry("900x500+50+50") # heightxwidth+x+y
mainPanel = Canvas(Window, width = 900, height = 500) # main screen
mainPanel.pack()
anyvar = StringVar() # the text in the entry
entry = Entry(mainPanel, width = 40, font = ("Purisa", 12, "bold"), justify = "center", textvariable = anyvar) # the entry
mainPanel.create_window(200, 100, window = entry)
anyvar.set("This doesnt work!!!!!")
Window.mainloop()
#Create()
If I run this library by itself then everything works fine, but when I import it from another program the only thing which doesn't work is anyvar.set("This doesnt work!!!!!").
Here is where I import it: (most of this code is cut out)
from tkinter import *
Window = Tk()
import make_entry
make_entry.Create()
Window.mainloop()
Is there a way to fix this problem without removing any of the windows?
You have two instances of Tk() which confuses Tkinter. I am guessing that the StringVar() is going to the other (first) instance. Instead, pass the only instance to the function, and use a Toplevel for a new window.
from tkinter import *
def Create(root):
window=Toplevel(root)
window.geometry("900x500+50+50") # heightxwidth+x+y
mainpanel = Canvas(window, width = 900, height = 500) # main screen
mainpanel.pack()
anyvar = StringVar() # the text in the entry
entry = Entry(mainpanel, width = 40, font = ("Purisa", 12, "bold"), justify = "center", textvariable = anyvar) # the entry
mainpanel.create_window(200, 100, window = entry)
anyvar.set("This doesnt work!!!!!")
and
from tkinter import *
Window = Tk()
import make_entry
make_entry.Create(Window)
Window.mainloop()