Enter button doesn't trigger - python-3.x

i am trying to open a google search window using python and the enter button trigger doesn't work.
so if you press the enter button it should open the window but it doesn't.
i am also using tkinter for gui.
help me :( thanks
(i am using win 10)
import tkinter as tk
def keyup():
opener()
def opener():
import webbrowser
text = name.get().strip()
query=str(text)
webbrowser.open("www.google.com/search?rlz=1C1CHZL_koUS766US766&ei=rDxSWtPFOeKt0gK4_YioDg&q="+query)
def clear():
name.delete(0, 'end')
root = tk.Tk()
ler=tk.Label(root, text = "what do you want to search?",font=("Helvetica", 40))
ler.pack()
name = tk.Entry(root,width=100)
name.pack()
widget=tk.Button(root, text = 'search', command =opener,width=30,height=3)
widget.pack()
widget.bind('<Enter>', opener)
wider=tk.Button(root, text = 'clear', command =clear,width=10,height=3)
wider.pack()
root.mainloop()
how do i fix this?

You have few mistakes
for key "Enter" is event <Return>. You can also assign <Return> to root and it works even when button is not selected/focused.
root.bind('<Return>', opener)
or assign to Entry
name.bind('<Return>', opener)
and "Enter" will run opener only when Entry is focused.
command= executes function without arguments but bind() executes function with one argument so you have to define function with argument which has default value and then it will work with both.
def opener(event=None):
use http:// in url because you can use file:// to open local file. On Linux link without http:// is treated as local file.
Smaller mistakes: put all import at top to make code more readable, Entry returns string so you don't need str()
EDIT: added name.bind('<Return>', opener)
import tkinter as tk
import webbrowser
def opener(event=None):
text = name.get().strip()
webbrowser.open("http://www.google.com/search?q="+text)
def clear():
name.delete(0, 'end')
root = tk.Tk()
ler=tk.Label(root, text="what do you want to search?", font=("Helvetica", 40))
ler.pack()
name = tk.Entry(root,width=100)
name.pack()
name.bind('<Return>', opener) # added
widget=tk.Button(root, text='search', command=opener, width=30, height=3)
widget.pack()
widget.bind('<Return>', opener)
wider = tk.Button(root, text='clear', command=clear, width=10, height=3)
wider.pack()
root.mainloop()

With Tk, the event binding <Enter is used to describe the cursor moving over the space occupied by the widget (entering the space). The binding you wish to use is <Return>, which is mapped to the return (enter) key on the keyboard.

I think it should be <Return> instead of <Enter>. Also, the indentations seem incorrect.

Related

multiple commands for a tkinter button

I have been trying to execute 2 commands in 1 button. I have read that using lambda can solve the problem. But my situation is a little different. On button press, one command is to destroy the existing GUI, and the second command, I want is to open another SERVER GUI. Below is my existing button functionality.
exit_button = Button(topFrame, text='Quit', command=window.destroy)
How can I open another GUI using same button?
Thank you for any help.
Edit:-
I have now created the below function:
def close_func():
os.kill(os.getpid(), signal.SIGINT)
GUI_Interface()
window.destroy()
server_socket.close()
GUI_Interface is a function that I need to call after closing the existing .py file. If I put GUI_Interface as the first command for close_func(), then it really does not go back to the 2nd step and never closes the existing.py file.
And if I place GUI_Interface in the end, it just closes the existing one and nevr opens the function of the new .py file
Three options at least:
using or (with lambda if arguments):
from tkinter import Tk, Button
root = Tk()
Button(root, text='Press', command=lambda: print('hello') or root.destroy() or print('hi')).pack()
root.mainloop()
important to use or because and didn't work (don't know why or how this works at all)
or use function definitions:
from tkinter import Tk, Button
def func():
print('hello')
root.destroy()
print('hi')
root = Tk()
Button(root, text='Press', command=func).pack()
root.mainloop()
or lists with lambda:
from tkinter import Tk, Button
def func():
print('hello')
root.destroy()
print('hi')
root = Tk()
Button(root, text='Press', command=lambda: [print('hello'), root.destroy()]).pack()
root.mainloop()

How to forget buttons created by a loop?

I need to create buttons with a for loop, here its an example of what i need to do:
But the problem is that when I press the different buttons, its prints the correct number, but it only forgets the last button created (in this case the button "4").
How can i do to forget all the buttons at once by only pressing one of them?
Its important the creation of the buttons by the loop
import tkinter as tk
root=tk.Tk()
def Eliminate(Number):
def Forget(number):
button.pack_forget()
print(number)
for i in range(Number):
button= tk.Button(root,text=i,command=lambda number=i:Forget(number))
button.pack()
Eliminate(5)
root.mainloop() ```
You need to pass in the button widget itself, not the number that created it. To do that you simply need to issue the command argument in a new line, like this:
import tkinter as tk
def Forget(btn):
btn.pack_forget()
def Eliminate(Number):
for i in range(Number):
button= tk.Button(root,text=i)
button.config(command=lambda button=button:Forget(button))
button.pack()
root=tk.Tk()
Eliminate(5)
root.mainloop()
However as the command is only calling the pack_forget method, it's much easier to forget making your own callback function and just provide pack_forget:
import tkinter as tk
def Eliminate(Number):
for i in range(Number):
button= tk.Button(root,text=i)
button.config(command=button.pack_forget)
button.pack()
root=tk.Tk()
Eliminate(5)
root.mainloop()

stop ttk.Entry() from reading keyboard

Environment: macOS Catalina, Python 3.7.4, Tcl/Tk 8.6.9, VSC 1.39.1
I have a situation where I am using a bar/qr code scanner to provide a string to a ttk.Entry() method, which then fires off a function.
The reader is seen by the OS as an HID keyboard, so the text from the QR code is received by the ttk.Entry() widget that I give focus to during code execution. I have bound the widget to the key because the scanner sends a cr/lf at the end of the text string, which works as needed.
However, I am running into an issue where if the qr code lingers over the scanner too long it will rescan the qr code and the widget receives the qr code text again, which then causes it to be processed again.
I have tried disabling the ttk.Entry() in the function, deleting the widget contents, and removing focus to no avail. The behavior I'm seeing is occurring even though the widget is disabled and does not have focus, it is still getting input and executing the function again if the scanner rescans the qr code while the function is executing.
In this first example, I simply tried to disable the widget, but that doesn't work. The widget still gets the later scans while in the function.
# test-ttk-entry1.py
import time
import tkinter as tk
from tkinter import StringVar, ttk
root = tk.Tk()
def print_text(event):
global kbEntry
textValue = kbEntry.get()
kbEntry.configure(state="disabled")
time.sleep(2) # Add in a delay to allow for repeat scan
print(textValue)
time.sleep(2) # Add in a delay to allow for repeat scan
kbEntry.configure(state="active")
kbText = StringVar()
kbEntry = ttk.Entry(root, width=10, textvariable=kbText)
kbEntry.bind("<Return>", print_text)
kbEntry.pack()
kbEntry.focus_set()
root.mainloop()
The second attempt was to disable the entry widget and upon making it active again delete the text in the field.
# test-ttk-entry2.py
import time
import tkinter as tk
from tkinter import END, StringVar, ttk
root = tk.Tk()
def print_text(event):
global kbEntry
textValue = kbEntry.get()
kbEntry.delete(0, END)
kbEntry.configure(state="disabled")
time.sleep(2) # Add in a delay to allow for repeat scan
print(textValue)
time.sleep(2) # Add in a delay to allow for repeat scan
kbEntry.configure(state="active")
kbEntry.delete(0, END)
kbText = StringVar()
kbEntry = ttk.Entry(root, width=10, textvariable=kbText)
kbEntry.bind("<Return>", print_text)
kbEntry.pack()
kbEntry.focus_set()
root.mainloop()
And finally, I was reading about taking focus from a widget and giving focus to the root window, so I added that in and it still prints multiple times to the console like there is a keyboard buffer being read by the ttk.Entry() widget. The weird thing is it seems like widgets don't normally respond to any calls to methods when they are disabled, but it appears the ttk.Entry() widget's properties/attributes (excuse me if my OOP terms are not correct) can be manipulated while disabled.
# test-ttk-entry2.py
import time
import tkinter as tk
from tkinter import END, StringVar, ttk
root = tk.Tk()
def print_text(event):
global kbEntry
textValue = kbEntry.get()
kbEntry.delete(0, END)
kbEntry.configure(state="disabled")
root.focus_set()
time.sleep(2) # Add in a delay to allow for repeat scan
print(textValue)
time.sleep(2) # Add in a delay to allow for repeat scan
kbEntry.configure(state="active")
kbEntry.delete(0, END)
kbEntry.focus_set()
kbText = StringVar()
kbEntry = ttk.Entry(root, width=10, textvariable=kbText)
kbEntry.bind("<Return>", print_text)
kbEntry.pack()
kbEntry.focus_set()
root.mainloop()
So how can I prevent the ttk.Entry() widget from accepting any input from the HID/keyboard device while my function is executing?
Since I am unable to find a way to temporarily disable the .Entry() widget programmatically to keep it from reading successive inputs, I have come up with this solution:
# test-ttk-entry2.py
import time
import tkinter as tk
from tkinter import END, StringVar, ttk
root = tk.Tk()
tempStr = "" # Global temporary string variable to trip repeated scans
def print_text(event):
global tempStr
textValue = kbEntry.get()
if tempStr == textValue:
kbEntry.delete(0, END)
print ("Duplicate scan")
return
tempStr = textValue
kbEntry.delete(0, END)
print(textValue)
time.sleep(3) # Simulate the time it takes for the function to complete
kbEntry = ttk.Entry(root, width=10)
kbEntry.bind("<Return>", print_text)
kbEntry.grid(row=0, column=0, padx=10, pady=10)
kbEntry.focus_set()
root.mainloop()

Getting an error while inserting values from the tkinter GUi to the database

Getting an error while inserting values from the tkinter GUi to the sqlite3 database.
Taking input from the user
By the tone of your question, it seems like you are having trouble accessing what is inside the text box.
An answer would be the .get() method. This basically allows you to access what is inside the text box.
Here is a simple code:
from tkinter import *
window = Tk()
window.title("Example")
window.geometry("500x500")
window.configure(bg = "sky blue")
e = Entry(window, bg = "blue", fg = "orange")
e.pack()
def com1():
acess = e.get()
print(acess)
button1 = Button(window, text = "enter", command = com1)
button1.pack()
The e.get() is what takes the stuff inside the Entry widget.
You save it in a variable, then use the variable for whatever you want.
Hope this helps!!!

Issue with tkinter Root Window and Radio Button GUI Generation

As someone new to tkinter for Python 3, I am having a couple of little issues navigating how to generate a GUI (in context of a Python script) despite reading the documentation and Stack Overflow answers. My objective is to create a frame with 7 radio button choices each corresponding to a screen resolution size which when selected and the submit button is pressed, the selected radio button will pass its value to a variable. However when I implement my GUI, I get two issues.
The first is that my frame opens correctly with the radio buttons, but another frame, which is blank and is titled "tk" appears. Regardless of what I do (i.e. use root.withdraw() etc. as others have mentioned), this blank window still appears.
The second and more baffling issue I am having is that when generated, all but the first radio button is selected, not normally with a dot in the center, but with a hyphen. Now the user can press on the option he/she wants and it will all unselect except for the choice, but it doesn't look normal and would probably confuse the user. I read about setting tristatevariable to none yet that didn't work (or at least in my trial). I also tried to force a deselect() function on all of the radio buttons before they generate and that didn't work either. Also, keep in mind that the radio buttons' variable must handle a string and not an int. What is happening here and how can I fix it?
The code snippet that pertains to both of these seemingly related issues is as follows:
if urldata == None:
class ResolutionInputGUI:
def __init__(self, master):
self.master = master
master.title("My GUI")
self.label = tk.Label(master, text="Your Screen Resolution Is: " + screenres + "\n")
self.label.pack()
MODES = [
("500×500", "500×500"),
("1280×800", "1280×800"),
("1280×1024", "1280×1024"),
("1440×900", "1440×900"),
("1680×1050", "1680×1050"),
("1920×1080", "1920×1080"),
("1920×1200", "1920×1200")
]
resolution = tk.StringVar()
resolution.set("500×500")
for text, mode in MODES:
self.radiobutton = tk.Radiobutton(master, text=text, variable=resolution, value=mode)
self.radiobutton.pack(anchor=tk.W)
self.submit_button = tk.Button(master, text="Submit", command=self.submit)
self.submit_button.pack()
self.cancel_button = tk.Button(master, text="Cancel", command=self.cancelbutton)
self.cancel_button.pack()
def submit(self):
global screenres
screenres = self.radiobutton.get()
root.quit()
self.master.destroy()
print(screenres)
def cancelbutton(self):
raise SystemExit
root = tk.Tk()
my_gui = ResolutionInputGUI(root)
root.mainloop()
Any help would be greatly appreciated as I cant seem to solve this issue and tkinter seems to be much more complicated than originally thought. Also, is there anything else that I am doing inefficiently here or to make the end user experience more "friendly?" Thank you so much!
The first is that my frame opens correctly with the radio buttons, but another frame, which is blank and is titled "tk" appears
This is because you are calling Tk() twice. I see one of them near the end, and you must have another elsewhere in your code.
all but the first radio button is selected, not normally with a dot in the center, but with a hyphen.
This is because you are using a local variable. Change "resolution" to "self.resolution".
when selected and the submit button is pressed, the selected radio button will pass its value to a variable
To do this you need to return the value from the variable, not from the button.
Also, you should put the class definition at the global level.
import tkinter as tk
class ResolutionInputGUI:
def __init__(self, master):
self.master = master
master.title("My GUI")
self.label = tk.Label(master, text="Your Screen Resolution Is: " + screenres + "\n")
self.label.pack()
MODES = [
("500×500", "500×500"),
("1280×800", "1280×800"),
("1280×1024", "1280×1024"),
("1440×900", "1440×900"),
("1680×1050", "1680×1050"),
("1920×1080", "1920×1080"),
("1920×1200", "1920×1200")
]
self.resolution = tk.StringVar(master, value="500×500")
for text, mode in MODES:
self.radiobutton = tk.Radiobutton(master, text=text, variable=self.resolution, value=mode)
self.radiobutton.pack(anchor=tk.W)
self.submit_button = tk.Button(master, text="Submit", command=self.submit)
self.submit_button.pack()
self.cancel_button = tk.Button(master, text="Cancel", command=self.cancelbutton)
self.cancel_button.pack()
def submit(self):
global screenres
screenres = self.resolution.get()
root.quit()
self.master.destroy()
print(screenres)
def cancelbutton(self):
raise SystemExit
if urldata == None:
root = tk.Tk()
my_gui = ResolutionInputGUI(root)
root.mainloop()

Resources