How to get content of ScrolledText? - python

I'm trying to get content of a ScrolledText but so far success is not with me :)
I don't understand where i'm wrong.
Here a very simple example of not working code...
from Tkinter import Tk
from ScrolledText import ScrolledText
def returnPressed(value):
print "CONTENT: " + value
root = Tk()
st = ScrolledText(root)
st.bind("<Return>", lambda event, i=st.get("1.0", "end-1c"): returnPressed(i))
st.insert("insert", "TEST")
st.pack()
root.mainloop()

Ok this is because of lambda definition.
By this way, function is created with constant "i" value, which is the value at declaration of function.
By rewording lambda as it, it works!
st.bind("<Return>", lambda event: returnPressed(st.get("1.0", "end-1c")))

You are getting the value at the time you create the button, which means the value will always be empty. You need to get the value at the time that the event is processed.
You should avoid using lambda, it is a somewhat advanced concept that in this case adds complexity without adding any value. Simply get the value from within the function:
def returnPressed(event):
value = event.widget.get("1.0", "end-1c")
print "CONTENT: " + value
...
st.bind("<Return>", returnPressed)

Related

Tkinter automatically update Label after Entry in Python

I made an tkinter window for some kind of calculation from the data entered. I simplified my code below to illustrate my question. Currently, the result will show up once I click search. However, I want the result to show up automatically once text are entered in the entry box without the "search" button. I tried "after" using window.after(100, self.searchbarcode) but it did not work for me. Appreciate your inputs. Thank you!
from tkinter import *
import pandas as pd
import tkinter as tk
import os.path
import numpy as np
class searchloc:
def __init__(self):
window=tk.Tk()
window.geometry("800x300")
window.title("Search Location")
Label(window, text="Scan",font="Helvetica 24").grid(row=1,column=1,sticky=W)
self.barcode=StringVar()
self.outcomes=StringVar()
self.text1=tk.Entry(window,textvariable=self.barcode,font="Helvetica 36")
self.text1.grid(row=1,column=2,padx=(0,5))
Label(window,textvariable=self.outcomes,font="Helvetica 68 bold").grid(row=7,column=2,sticky=E)
wsheet1 = gsheet.worksheet("Sheet2")
mydata1 = wsheet1.get_values()
mydata2=mydata1[1:]
cool=mydata1[0]
look = pd.DataFrame(mydata2, dtype=str)
#window.after(1, self.searchbarcode())
#self.text1.bind('<Enter>', self.searchbarcode())
Button(window,text='search',command=self.searchbarcode,font="Helvetica 38").grid(row=5,column=2,padx=(100,5),pady=5,sticky=W)
#Button(window,text='clear',command=self.clear_text,font="Helvetica 38").grid(row=5,column=2,padx=(100,5),pady=5,sticky=E)
window.mainloop()
#def clear_text(self):
def searchbarcode(self):
bar = self.barcode.get()
outtt=bar[1:5]
self.outcomes.set(outtt)
self.text1.delete(0, 'end')
searchloc()
If you want to happen when you press the return key, you almost had it right. The function has to accept an event parameter even if you don't use it, and you need to make sure you pass the function itself, not the result of calling the function (ie: self.searchbarcode instead of self.searchbarcode()).
Also, the event is <Return>. <Enter> is for when the mouse enters the widget.
def __init__(self):
...
self.text1.bind('<Return>', self.searchbarcode)
...
def searchbarcode(self, event):
...
If you want to call searchbarcode both with or without the event parameter, give it a default value of None:
def searchbarcode(self, event=None):
...

Python: Get information after link binding partial Tkinter

import functools
from tkinter import *
win = Tk()
def func(win,name):
print (name)
mylist = ['item1','item2','item3']
for item in mylist:
link1=Label(win,text=item)
link1.bind("<Button-1>",functools.partial(func,item))
link1.pack()
win.mainloop()
My code currently outputs "ButtonPress event num=1 x=10 y=10>" whereas it should output item 1,2 or 3 when the label is pressed.
When buttons are used instead it works perfectly fine but once it's a binded Label it gives a different output
A Button command calls a function with no parameters func(). Any function bound to a "<Button-1>" event is passed the event, func(event).
In the original code:
def func(win,name):
print (name)
functools.partial(func,item)
# This sets the **win** parameter to item. When the new function is called
# the **event** is passed to the next 'available' parameter, name.
This works when the partial is called from a button command as no parameters are passed. When called from a bound event an event parameter is passed. This is what is printed when the Label is clicked.
import functools
from tkinter import *
win = Tk()
def func( event, name ):
print ("Event: ", event, "Name: ", name)
mylist = ['item1','item2','item3']
for item in mylist:
link1=Label(win,text=item)
link1.bind("<Button-1>",functools.partial(func,name = item))
# set the name parameter explicitly
link1.pack()
win.mainloop()

Binding and returning values from a function within a function (Tkinter)

I have simplified the issue I am having with my code.
I have several functions within functions and I am finding it difficult to capture a return value from a function which is trigged from a binding.
from tkinter import *
root = Tk()
root.title("Test example")
root.geometry("500x500")
def funcl(event):
print("funcl")
def inner_funcl():
print("inner fucntion")
x = 15
return x
x=inner_funcl()
return x
def ppprinter(x):
print(x)
z=funcl(event)
ppprinter(z)
my_button = Button(root,text="Button")
my_button.pack()
my_button.bind("<Button-1>",funcl)
root.mainloop()
z = funcl(event)
The event variable you are passing to the function is not declared. And the event passed in the function funcl is not used anywhere.
I do not get the point of this code and its functionality.
Solution:
You could create a variable event with any value (for example: event = "Hello").
This will allow you to run the script.

What caused the error

I am trying to make GUI that reverses the user input but something is wrong
from tkinter import *
from tkinter.ttk import *
def reverse(s):
s=U.get()
return s[::-1]
root=Tk(className="Reverse your text")
la=Label(root, text="Enter text to reverse")
la.pack()
U=Entry(root,textvariable=s)
U.pack()
BT=Button(root, text="reverse", command=reverse(s))
BT.pack()
root.mainloop()
Error: U=Entry(root,textvariable=s)
NameError: name 's' is not defined
def reverse(s): should not have an s if you don't intend to pass any arguments to the function. Likewise for command=reverse(s)
U=Entry(root,textvariable=s) does not need a textvariable if you're just going to access the Entry's value directly with .get. And anyway, you can't use s here, because you never assigned a StringVar object to s to begin with.
The value returned by return s[::-1] will not be visible in any way to the user. If you want to show the reversed string, you need to print it or insert it into the entry, or similar.
from tkinter import *
from tkinter.ttk import *
def reverse():
s=U.get()
U.delete(0, END)
U.insert(0,s[::-1])
root=Tk(className="Reverse your text")
la=Label(root, text="Enter text to reverse")
la.pack()
U=Entry(root)
U.pack()
BT=Button(root, text="reverse", command=reverse)
BT.pack()
root.mainloop()
Result:

tkinter get values from dynamic checkboxes

I am trying to create a number of dynamic checkboxes from data in a XML file.
I have no problems creating the button themselves, but I cant get the values generated by them.
Here is what I got so far...
#!/usr/bin/python3
from tkinter import *
from tkinter import ttk
import xml.etree.ElementTree as ET
root = Tk()
def Readstatus():
print(var.get())
listTree = ET.parse('list.xml')
listRoot = listTree.getroot()
var = dict()
count=1
for child in listRoot:
var[child]=IntVar()
chk = Checkbutton(root, text='Text'+str(count), variable=var[child], command=Readstatus)
count += 1
chk.pack()
root.mainloop()
Any help would be greatly apreciated!
Gilles
The event handler will return a TypeError as it expects 1 argument and got nothing. To make this a bit simpler, I modified the code so that it the key to the event handler.
from tkinter import *
from tkinter import ttk
import xml.etree.ElementTree as ET
root = Tk()
def Readstatus(key):
print(var.get(key))
listTree = ET.parse('test.xml')
listRoot = listTree.getroot()
var = dict()
count=1
for child in listRoot:
var[child]=IntVar()
chk = Checkbutton(root, text='Text'+str(count), variable=var[child],
command=lambda key=child: Readstatus(key))
count += 1
chk.pack()
root.mainloop()
This worked for me. I do think using Element objects for keys in the dictionary is a bit hard to debug, but I'm sure you have a good reason for doing that.
EDIT
To get just a 1 or 0 returned, change the event handler to look like this:
def Readstatus(key):
var_obj = var.get(key)
print(var_obj.get())
The var.get() command is actually calling a dictionary object's get() method, which is why it requires a key passed to it. Once you have the IntVar object returned, you can call its own get method to return the 0 or 1. See also:
http://effbot.org/tkinterbook/checkbutton.htm

Categories