This question already has answers here:
Entry box text clear when pressed Tkinter
(2 answers)
Closed 2 years ago.
I want to clear text box as soon as i click on it to write, Please help me to do this
from tkinter import *
from tkinter import ttk
root = Tk()
fileLable = Text(root, height = 1, width = 26 )
fileLable.insert(INSERT, "this text")
fileLable.grid(row = 0, column = 0,columnspan = 2, padx = (10,0),pady = (3,0))
submit = ttk.Button(root, text = "Submit", command = some_method)
submit.grid(row = 1, column = 1, padx = (10,0), pady = (10,0))
root.mainloop()
I know that this one :
def some_callback(event): # note that you must include the event as an arg, even if you don't use it.
e.delete(0, "end")
return None
So then how I catch this event when it is clicked on the text box to include above code to my main code
Please help thanks in advance 😊
You could try this below, bind events <FocusIn> and <FocusOut>:
from tkinter import *
from tkinter import ttk
def delText(event=None):
fileLable.delete("1.0", END)
root = Tk()
fileLable = Text(root, height = 1, width = 26 )
fileLable.insert(INSERT, "this text")
fileLable.grid(row = 0, column = 0,columnspan = 2, padx = (10,0),pady = (3,0))
fileLable.bind("<FocusIn>", delText)
submit = ttk.Button(root, text = "Submit")
submit.grid(row = 1, column = 1, padx = (10,0), pady = (10,0))
root.mainloop()
To call a function when a user clicks in a widget, you can bind to the <1> event. The function is passed an argument which contains information about the event, including a reference to the widget that received the event.
To delete all of the text in a text widget, call the delete method with the arguments "1.0" and "end".
Putting that together, it looks like this:
def clearText(event):
event.widget.delete("1.0", "end")
fileLable.bind("<1>", clearText)
Related
I am working with python tkinter and I have a dialog box window that pops up. I have two buttons in the box:
from tksheet import Sheet
from tkinter import *
import os
import sys
import mapMaker2
root=Tk()
root.title('Map Tool')
root.geometry("750x750")
sheetframe = Frame(root)
sheetframe.grid(row = 0, column = 0,)
buttonEditlabel = Button(sheetframe, text='Edit Labels', width=12, command=lambda: [openEditWindow()], bg='#cacccf',fg='black')
buttonEditlabel.grid(row = 0, sticky=W, column = 0, pady = (25,5), padx = (50,0))
def openEditWindow():
top = Toplevel(root)
top.geometry("260x195")
top.title('Edit Axes Labels')
frm = Frame(top, borderwidth=0, relief='ridge')
frm.grid(row = 0, column = 0, pady = (20,0),padx=(20,0))
b_cancel = Button(frm, text='Close', width=10)
b_cancel['command'] = top.destroy
b_cancel.grid(column = 0, row = 6, pady = (15,0),padx=(0,0))
b_save = Button(frm, text='Save', width=10)
b_save['command'] = lambda: editLabels()
b_save.grid(column = 1, row = 6, sticky = E, pady = (15,0),padx=(0,0))
def editLabels():
pass
mainloop()
Cancel button closes the window with top.destroy command. I would like the Save button to also close the window after running the editLabels() function first. I have tried:
b_save['command'] = [lambda: editLabels(), top.destroy]
but this doesn't work.
Here is one way you can do it. Create a function to destroy the top window.
def kill_main():
top.destroy()
top.update()
Then call the function wherever you want. You don't have to add kill_main() to the button itself. Just put it inside the next function you are opening so that it will close the Top windows first and then run the rest of the editlabels() function. Hopefully, it makes sense to you.
def editLabels():
kill_main()
pass
How to create large extry box in python tkinter?
I have tried to use height in ttk.entry() but the error show :
_tkinter.TclError: unknown option "-height"
from tkinter import *
from tkinter import ttk
GUI = Tk()
GUI.title("myTest")
GUI.geometry("700x700")
S_NOTE = StringVar()
E_NOTE = ttk.Entry(GUI, textvariable = S_NOTE, font = FONT1, width = 40, height = 20)
E_NOTE.grid(row = 0, column = 0, columnspan = 2, rowspan = 2)
GUI.mainloop()
I also need to get the StringVar from the entrybox and fix the position (such as using grid)
Looks like you are using a bad way to do this..
see.. You can use the Text widget to do the same..
Example:
from tkinter import *
GUI = Tk()
GUI.title("myTest")
GUI.geometry("700x700")
def set_text_to_variable():
global E_NOTE
global S_NOTE
S_NOTE = E_NOTE.get(1.0,END)
print("S_NOTE = ",S_NOTE)
E_NOTE = Text(GUI, font = "Segoe", width = 40, height = 20)
E_NOTE.grid(row = 0, column = 0, columnspan = 2, rowspan = 2)
Change_variable = Button(GUI, text = "CHANGE THE \"S_NOTE\" VARIABLE", command = set_text_to_variable)
Change_variable.grid()
GUI.mainloop()
I have a tkinter Entry widget and when a user presses a button the contents update:
from tkinter import *
window = Tk()
def abcdef(num):
ent.config(state=NORMAL)
ent.delete(0, 'end')
ent.insert(0, num)
ent.config(state = "readonly")
print(num) #Just to check the code is being run
def changeEntry():
for j in range(3):
ent.after(1000, abcdef(j))
ent = Entry(widow, text="", state = "readonly", readonlybackground="white", font = "20")
ent.grid(row = 0, column = 0, columnspan = 3, sticky = "E")
btn = Button(window, text="Button", command=changeEntry)
btn.grid(row = 1, column = 0, sticky = "NESW", pady = 10, padx = 10)
window.mainloop()
When I press the button the window freezes for 3 seconds and then just displays the final number. How can I make it so when the user presses the button, the entry changes every second instead of just freezing for 3 seconds and only displaying the final one?
Thanks in advance
You have two problems with that .after call. The .after method tells Tkinter to call the function you pass it after the time interval has passed. But you're telling Tkinter to do 3 things after 1000 milliseconds have passed, so they'll all happen on top of each other. So you need to stagger the delays.
Secondly, you need to give .after a function to call when its time to call it. But your code calls the function and gives .after the return value of your function. We can fix that by wrapping the function call inside another function. A convenient way to do that is using lambda, giving the lambda a default argument it can pass to abcdef
import tkinter as tk
window = tk.Tk()
def abcdef(num):
ent.config(state=tk.NORMAL)
ent.delete(0, 'end')
ent.insert(0, num)
ent.config(state = "readonly")
print(num) #Just to check the code is being run
def changeEntry():
for j in range(3):
ent.after(1000 * j, lambda num=j: abcdef(num))
ent = tk.Entry(window, text="", state = "readonly", readonlybackground="white", font = "20")
ent.grid(row = 0, column = 0, columnspan = 3, sticky = "E")
btn = tk.Button(window, text="Button", command=changeEntry)
btn.grid(row = 1, column = 0, sticky = "NESW", pady = 10, padx = 10)
window.mainloop()
I've also replaced that "star" import with the neater import tkinter as tk. That makes it obvious which names come from Tkinter and which names are local to your program.
Bryan Oakley points out that we don't need that lambda, we can pass in arguments after the function name. See the Basic Widget Methods in the Tkinter docs for details. So we can re-write changeEntry like this:
def changeEntry():
for j in range(3):
ent.after(1000 * j, abcdef, j)
Thanks, Bryan!
I want to read an input from entry widget and display it in canvas on clicking the button.I created a canvas and I tried this code
entryval= Tkinter.Entry(framename)
entryval.pack()
button = Tkinter.Button(entryframe, text ="Enter",command=print)
button.pack()
def print()
print entryval.get
But result is displaying only in terminal.not in canvas.
Please help.Thanks in advance
Here's a quick demo I made to help printing text to canvas:
from Tkinter import *
window = Tk()
def printVal():
canvas = Canvas(window, width = 100, height = 100)
canvas.grid(row = 0, column = 0, columnspan = 2)
string = entryval.get()
canvas.create_text(50,50, text = string)
entryval = Entry(window)
entryval.grid(row = 1, column = 0)
button = Button(window, text = "Print", command = printVal)
button.grid(row = 1, column = 1)
window.mainloop()
I am new to Tkinter. I am trying to create a GUI that has two spinboxes and two checkboxes whose values will be printed when a user clicks a particular button ("Start"). Here is my code so far:
from Tkinter import *
from tkFileDialog import askopenfilename
from PIL import Image
#create TK frame
root = Tk()
#identify the dimensions of the TK frame
root.geometry("360x150")
#title the TK frame
root.title("Literature Online API")
#create a function that will return the filepath for a file provided by the user
def selectfile():
user_defined_filepath['filename'] = askopenfilename(filetypes=[("Text","*.txt")]) # user_defined_filepath['filename'] may now be accessed in the global scope.
#create a function that will allow the "start" button to begin further processes
def startapi(event = "<Button>"):
print windowlengthspinbox.get()
print slideintervalspinbox.get()
print fuzzyspellingbutton.get()
print lemmatizedsearchbutton.get()
#create variables for the checkbuttons -- default = 0, checked = 1
fuzzyspellingvariable = IntVar()
lemmatizedsearchvariable = IntVar()
#create a caption that will appear as the first line of the grid
firstlinelabel = Label(root, text = "Please select any desired search options:")
firstlinelabel.grid(row = 0, column = 0, sticky = W)
#create a button that allows users to employ Literature Online's fuzzy spelling feature. Add the object.grid() method on new line because appending .grid() to the line in which one defines object causes Python to give the object attribute "NoneType." http://stackoverflow.com/questions/1101750/python-tkinter-attributeerror-nonetype-object-has-no-attribute-get
fuzzyspellingbutton = Checkbutton(root, text="Fuzzy Spelling", variable=fuzzyspellingvariable)
fuzzyspellingbutton.grid(row = 1, column = 0, sticky = W)
#create a button that allows users to employ Literature Online's lemmatized search feature
lemmatizedsearchbutton = Checkbutton(root, text="Lemmatized Search", variable=lemmatizedsearchvariable)
lemmatizedsearchbutton.grid(row = 2, column = 0, sticky = W)
#create a spinbox that allows users to identify desired window length
windowlengthspinbox = Spinbox(root, from_=1, to=10)
windowlengthspinbox.grid(row = 3, column = 1, sticky = W)
windowlengthspinboxlabel = Label(root, text = "Please select window size")
windowlengthspinboxlabel.grid(row = 3, column = 0, sticky = W)
#create a spinbox that allows users to identify desired window length
slideintervalspinbox = Spinbox(root, from_=1, to=10)
slideintervalspinbox.grid(row = 4, column = 1, sticky = W)
slideintervalspinboxlabel = Label(root, text = "Please select window slide interval")
slideintervalspinboxlabel.grid(row = 4, column = 0, sticky = W)
#create a button that allows users to find a file for analysis
selectfilebutton = Button(root,text="Select File",command=selectfile)
selectfilebutton.grid(row = 5, column = 0, sticky = W)
#create a start button that allows users to submit selected parameters and file
startbutton = Button(root, text="Start", command = startapi, width = 8)
startbutton.grid(row = 5, column = 1, sticky = E)
startbutton.bind("<Button>", startapi)
#startbutton.focus()
#instantiate the Tk window
root.mainloop()
When I click the "Start" button, the GUI prints the values of the spinboxes, then tells me that Checkbutton instance has no attribute 'get':
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1410, in __call__
return self.func(*args)
File "groundupgui.py", line 20, in startapi
print fuzzyspellingbutton.get()
AttributeError: Checkbutton instance has no attribute 'get'
Does anyone know how I can print the values of the checkboxes? I would be grateful for any suggestions or insight.
To find the state of the Checkbutton use the fuzzyspellingvariable that you've attached to the Checkbutton:
fuzzyspellingvariable.get()
By the way, since the checkbutton only has two states, you could use a BooleanVar instead of an IntVar here:
fuzzyspellingvariable = BooleanVar()
Ah, I got it. You need to perform the .get() method on the variable, not the button:
print fuzzyspellingvariable.get()
print lemmatizedsearchvariable.get()