I'm trying to clear a Tkinter Entry Box by using a Tkinter Button. The problem is that my entry includes both 'Integers' aswell as a 'String' and my code wont clear the entry.
I have tried changing the attributes of the clearing method. Right now it's .delete(0, END). But i have tried changing it to .delete("0.0", END) and .delete(0.0, END. But this is just me desperatly trying things out.
enter code here
from tkinter import *
root = Tk()
def validatecontent(entry_text1):
return (entry_text1.isdigit() == bool(entry_text1)) or entry_text1 ==
(".")
def clear_entry():
entry_1.delete(0, END)
vcmd = (root.register(validatecontent), '%S')
entry_text1 = StringVar()
entry_1 = Entry(root, width=11, textvariable=entry_text1,
validate='all', validatecommand=vcmd)
entry_1.pack()
button = Button(root, width=10, text="Clear",
command=clear_entry)
button.pack()
root.mainloop()
If the entry contains Integers alone it gets cleared. But if the entry contains '.' nothing happens, no error code at all.
Related
I am new in python
I wanted to make a program that when you write a specific string in entry it compares it with a string and get an output but it doesnt go well ,where is the mistake i have done?
from tkinter import *
from tkinter.ttk import *
app=Tk()
load = Entry(app, width=10)
loadvar = StringVar
z = loadvar.get()
if z == "winner"
Label(app,text="congrats",).grid(row=1,column=0)
app.mainloop()
from tkinter import *
from tkinter.ttk import *
app = Tk()
# Entry
loadvar = StringVar()
load = Entry(app, width=10, textvariable=loadvar)
load.grid(row=0, column=0)
load.focus()
def compare():
if loadvar.get() == "winner":
# Label
Label(app, text="congrats", ).grid(row=1, column=0)
# Button
Button(text="Compare", command=compare).grid(row=0, column=1)
app.mainloop()
In your code, you have not placed the Entry widget yet. Moreover, you should use Buttons and link them with the function you want so that you can carry it out each time you are using it. Otherwise, you are check if the text inside entry is equal to 'winner' even before typing into it.
loadvar = StringVar
This line must be before creating Entry and then put in "textvariable" attribute of the widget.
I am new to programming and Tkinter. I want to DISABLED textbox when checkbox is pressed and open it NORMAL when box is not ticked. Here is my code:
from tkinter import *
root = Tk()
def lock_fields():
if check == True:
data.configure(state=DISABLED)
if check == False:
data.configure(state=NORMAL)
check = BooleanVar()
open_for_edit = Checkbutton(root, text="check the box for editing", variable=check,
onvalue=True, offvalue=False, command=lambda: lock_fields())
open_for_edit.pack()
check = check.get()
data = Text(root)
data.insert(END, "I would like to be able to edit this text only when checkbox is checked.")
data.pack()
root.mainloop()
It seems that for some reason the check-variable is always False when it enters to lock_fields function. I tried passing check argument to the method.
You're pretty close, only thing is that the check.get() line must be in the function. Also you don't need the lambda. Try this:
from tkinter import *
root = Tk()
def lock_fields():
if check.get():
data.configure(state=DISABLED)
else:
data.configure(state=NORMAL)
check = BooleanVar()
open_for_edit = Checkbutton(root, text="check the box for editing", variable=check, onvalue=True, offvalue=False, command=lock_fields)
open_for_edit.pack()
data = Text(root)
data.insert(END, "I would like to be able to edit this text only when checkbox is checked.")
data.pack()
root.mainloop()
I want a checkbox that when check, creates a scrolled text widget and when unchecked, removes the widget.
Currently it creates the widget only once I've checked the box and then unchecked it, and then when checked again, it does nothing and when unchecked again, it creates a second widget below.
I've tried different ways of coding it but I can't figure out what I'm doing wrong.
# Creates Normal Checkbutton
chk_state = BooleanVar()
chk_state.set(False) # set check state
chk = Checkbutton(window, text='Normal Entries', var=chk_state)
chk.place(x=0, y=0)
#Checks Checkbutton State
def chk_checked(event):
txt = scrolledtext.ScrolledText(window, height=15, width=35)
if chk_state.get():
txt.insert(END, 'Paste Normal Entries Here...')
txt.pack(anchor='nw', padx=50, pady=50)
elif txt.winfo_exists():
txt.pack_forget()
else:
pass
#Event when checkbox checked
chk.bind('<Button-1>', chk_checked)
You can try as this
import tkinter as tk
from tkinter.scrolledtext import ScrolledText
def chk_checked():
global txt
if chk_state.get():
txt = ScrolledText(window, height=15, width=35)
txt.insert(tk.END, 'Paste Normal Entries Here...')
txt.pack(anchor='nw', padx=50, pady=50)
else:
txt.pack_forget()
window = tk.Tk()
chk_state = tk.BooleanVar()
chk_state.set(False) # set check state
chk = tk.Checkbutton(window, text='Normal Entries', var=chk_state, command=chk_checked)
chk.place(x=0, y=0)
txt = None
window.mainloop()
This isn't the best way for do that, maybe you can create a class, i think that would be better.
The problem with your code is that each time that you click the CheckButton the function chk_checked(event) creates a new ScrolledText and after works on it instead working on the ScrolledText that was created previously. You have to declare a global variable (instead of a local variable) in wich you store the ScrolledText that you want to use and work only with it
I just want that when I type my name inside the entry box then appears in another entry with some add text. The idea is type in the entry below and after that it showed in the big entry.I was looking for this solution, but just found place in Label. I don't want in Label. The window is more big, must drag to show the entry. There's is a picture that i use in this script:
from tkinter import *
from PIL import Image, ImageTk
root = Tk()
cat = Entry(root)
cat.place(x=48, y=25, width= 350, height=140)
user = Entry(root)
user.place(x=75, y=550)
btn = Button(root, text='START')
btn.place(x=220, y=410)
root.mainloop()
#
Ok, It works the way you told me,thank you!
But now i'm facing another problem.
The problem is when i insert the function of the game in the second window. I tested in one window and it works, but when i place the function in the second window gives an error when i press the "Start" button:
'''user_try = int(txt.get())
NameError: name 'txt' is not defined'''
When i press reset button gives another error:
'''user_try = int(txt.get())
NameError: name 'txt' is not defined'''
So i know that is missing definition, but i don't know how to make a reference for this command that it's in the second window. Like i said running with just one window the program works.
Maybe i should make using class, i don't know, but i wish to make this way that i started. However if there's no other way to do as i'm doing, let's go.
I just simplify the script here, actualy the main script is more bigger, so my idea is when open the program, there is a window and the user read the instructions about the game and proceed open the second window. The window have pictures and some hidden buttons in the next picture, so there will be an interactivity with the environment.
The guess number is just the beggining. After that there will be new challeges.
I'm very excited doing this, but i'm stuck in this point. The part one i finished, the pictures, the hidden buttons it's exacly the way i want, but the challenge stops here in this problem.
from tkinter import *
from PIL import Image, ImageTk, ImageSequence
import random
from tkinter import messagebox
pc = random.randint(1,10)
def reset():
global pc
pc = random.randint(1,10)
cat['text'] = 'Ok! Lets Try Again!'
def openwin2():
win1.withdraw()
win2 = Toplevel()
win2.geometry('350x300+180+100')
win2.title('second window')
txt = Entry(win2)
txt.place(x=10,y=10)
cat = Label(win2,wraplength=300)
cat.place(x=10,y=50)
cat.config(text='Hi! I Am thinking a number between 1 and 10.')
btn = Button(win2,text='start',command=check)
btn.place(x=30, y=150)
btn2 = Button(win2, text='reset', command=reset)
btn2.place(x=110,y=150)
win2.mainloop()
def check():
user_try = int(txt.get())
if user_try < pc:
msg = 'Hmmmm... the number, which I thought of, is greater than this.'
elif user_try > pc:
msg = 'How about trying a smaller number ?!'
elif user_try == pc:
msg = 'Well Done! You guessed! It was %s the number!' % user_try
else:
msg = 'Something Went Wrong...'
cat['text'] = msg
win1 = Tk()
win1.title('First Window')
win1.geometry('350x300')
user = Label(win1,text='first window')
user.place(x=10,y=10)
btn1 = Button(win1,text='Open Window 2', command=openwin2)
btn1.place(x=10,y=50)
win1.mainloop()
There are multiple ways to do this in tkinter, here's a rework of your code using StringVar objects set to the textvariable properties of your Entry objects:
import tkinter as tk
def doit():
out_string.set("Hello " + in_string.get())
root = tk.Tk()
in_string = tk.StringVar()
out_string = tk.StringVar()
cat = tk.Entry(root, textvariable=in_string)
cat.place(x=20, y=25, width=100)
user = tk.Entry(root, textvariable=out_string)
user.place(x=20, y=75)
btn = tk.Button(root, text='START', command=doit)
btn.place(x=20, y=150)
root.mainloop()
Per #Mike-SMT, here's a different approach using Entry.get() and Entry.insert(). It augments the text when the user clicks the button:
import tkinter as tk
def doit():
user.insert(tk.END, cat.get())
root = tk.Tk()
cat = tk.Entry(root)
cat.place(x=20, y=25, width=100)
user = tk.Entry(root)
user.place(x=20, y=75)
user.insert(0, "Hello ")
btn = tk.Button(root, text='START', command=doit)
btn.place(x=20, y=150)
root.mainloop()
However, you'll see that subsequent button clicks keep appending the text. When working with Entry.insert(), you need to work with Entry.delete() and/or other Entry methods to properly manipulate the text.
I'm trying to use an Entry field to get manual input, and then work with that data.
All sources I've found claim I should use the get() function, but I haven't found a simple working mini example yet, and I can't get it to work.
I hope someone can tel me what I'm doing wrong. Here's a mini file:
from tkinter import *
master = Tk()
Label(master, text="Input: ").grid(row=0, sticky=W)
entry = Entry(master)
entry.grid(row=0, column=1)
content = entry.get()
print(content) # does not work
mainloop()
This gives me an Entry field I can type in, but I can't do anything with the data once it's typed in.
I suspect my code doesn't work because initially, entry is empty. But then how do I access input data once it has been typed in?
It looks like you may be confused as to when commands are run. In your example, you are calling the get method before the GUI has a chance to be displayed on the screen (which happens after you call mainloop.
Try adding a button that calls the get method. This is much easier if you write your application as a class. For example:
import tkinter as tk
class SampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.entry = tk.Entry(self)
self.button = tk.Button(self, text="Get", command=self.on_button)
self.button.pack()
self.entry.pack()
def on_button(self):
print(self.entry.get())
app = SampleApp()
app.mainloop()
Run the program, type into the entry widget, then click on the button.
You could also use a StringVar variable, even if it's not strictly necessary:
v = StringVar()
e = Entry(master, textvariable=v)
e.pack()
v.set("a default value")
s = v.get()
For more information, see this page on effbot.org.
A simple example without classes:
from tkinter import *
master = Tk()
# Create this method before you create the entry
def return_entry(en):
"""Gets and prints the content of the entry"""
content = entry.get()
print(content)
Label(master, text="Input: ").grid(row=0, sticky=W)
entry = Entry(master)
entry.grid(row=0, column=1)
# Connect the entry with the return button
entry.bind('<Return>', return_entry)
mainloop()
*
master = Tk()
entryb1 = StringVar
Label(master, text="Input: ").grid(row=0, sticky=W)
Entry(master, textvariable=entryb1).grid(row=1, column=1)
b1 = Button(master, text="continue", command=print_content)
b1.grid(row=2, column=1)
def print_content():
global entryb1
content = entryb1.get()
print(content)
master.mainloop()
What you did wrong was not put it inside a Define function then you hadn't used the .get function with the textvariable you had set.
you need to put a textvariable in it, so you can use set() and get() method :
var=StringVar()
x= Entry (root,textvariable=var)
Most of the answers I found only showed how to do it with tkinter as tk. This was a problem for me as my program was 300 lines long with tons of other labels and buttons, and I would have had to change a lot of it.
Here's a way to do it without importing tkinter as tk or using StringVars. I modified the original mini program by:
making it a class
adding a button and an extra method.
This program opens up a tkinter window with an entry box and an "Enter" button. Clicking the Enter button prints whatever is in the entry box.
from tkinter import *
class mini():
def __init__(self):
master = Tk()
Label(master, text="Input: ").grid(row=0, sticky=W)
Button(master, text='Enter', command=self.get_content).grid(row=1)
self.entry = Entry(master)
self.entry.grid(row=0, column=1)
master.mainloop()
def get_content(self):
content = self.entry.get()
print(content)
m = mini()