page GUI - Combobox pass variable - python

New to GUI. Not quite getting there. I used page and get can get buttons to do something (click on a button and get a response). With Combobox, I can't pass a value. Searched here, tried many things, watched a few hours of youtube tutorials.
What am I doing wrong below? This is the code page generates (basically) then I added what I think I need to do to use the Combobox.
I am just trying to have 1,2,3 in a combo box and print out the value that is chosen. Once I figure that out I think I can actually make a simple GUI that passes variables I can then program what I want to do with these variables being selected.
class New_Toplevel_1:
def __init__(self, top):
self.box_value = StringVar()
self.TCombobox1 = ttk.Combobox(textvariable=self.box_value)
self.TCombobox1.place(relx=0.52, rely=0.38, relheight=0.05, relwidth=0.24)
self.TCombobox1['values']=['1','2','3']
self.TCombobox1.configure(background="#ffff80")
self.TCombobox1.configure(takefocus="")
self.TCombobox1.bind('<<ComboboxSelected>>',func=select_combobox)
def select_combobox(self,top=None):
print 'test combo ' # this prints so the bind works
self.value_of_combo = self.ttk.Combobox.get() # this plus many other attempts does not work

It's hard to know what you're actually asking about, since there is more than one thing wrong with your code. Since you say the print statement is working, I'm assuming the only problem you have with your actual code is with the last line.
To get the value of the combobox, get the value of the associated variable:
self.value_of_combo = self.box_value.get()
Here's a working version where I fixed the other things that were wrong with the program:
from tkinter import *
from tkinter import ttk
class New_Toplevel_1:
def __init__(self, top):
self.box_value = StringVar()
self.TCombobox1 = ttk.Combobox(textvariable=self.box_value)
self.TCombobox1.place(relx=0.52, rely=0.38, relheight=0.05, relwidth=0.24)
self.TCombobox1['values']=['1','2','3']
self.TCombobox1.configure(background="#ffff80")
self.TCombobox1.configure(takefocus="")
self.TCombobox1.bind('<<ComboboxSelected>>',func=self.select_combobox)
def select_combobox(self,top=None):
print('test combo ') # this prints so the bind works
self.value_of_combo = self.box_value.get()
print(self.value_of_combo)
root = Tk()
top = New_Toplevel_1(root)
root.mainloop()
Note: I strongly advise you not to start with place. You should try to learn pack and place first. I know place seems easier, but to get the most responsive and flexible GUI you should leverage the power of pack and grid.

Related

Hi , How can I change a string number from Entry of tkinter into int number?

Hi i'm a beginner in python and I really got int trouble with some methods, I wanna give some number from Entry of tkinter class and show them with a chart,
but the thing is that I cant get int number:
so the chart wont work [here is the picture of my code , I get some bumber from entry but i cant make them integer number]
1: https://i.stack.imgur.com/2Vuvn.jpg
2: https://i.stack.imgur.com/Pa23V.jpg
Welcome. I'm posting a complete, I think, answer to this question but there are a couple of etiquette things you should know:
Please don't post screenshots of your code. Copy and paste into the editor.
Please post just enough code to show your problem, but which is complete enough that we can just copy it into our own editors / IDEs and run without a lot of modification.
The previous commenters are correct that this question has probably been answered a hundred times, so please try to search through previous answers before posting your question.
Having said that, I have not answered this question before, so here's my rendition. I know you're a beginner so I've tried to keep it as simple as possible, but you're also tackling TKinter so I've not made it overly simplistic.
import tkinter as tk
def main():
global entryVar, lableVar
#create a tkinter window:
rootWin = tk.Tk() #creates a root window
rootWin.title('Entry Test') #shows text on the title bar
rootWin.geometry('500x200') #sets the displayable size of the window
#we'll need these variables and they MUST be tk.StringVar()
entryVar = tk.StringVar() #variable to hold the entry value
lableVar = tk.StringVar() #variable to hold the lable value
#create an entry widget:
entry = tk.Entry(
rootWin,
width = 5,
textvariable = entryVar
)
entry.pack(expand=1)
entry.bind('<Return>', getEntryValue) #bind enter key to widget
entry.bind('<KP_Enter>', getEntryValue, add='+') #bind the other enter key to widget
#create a lable widget
lable = tk.Label(
rootWin,
textvariable = lableVar
)
lable.pack(expand=1)
lableVar.set("This is where the lable is.")
entry.focus_set() #set focus on the entry widget for convenience
rootWin.mainloop()
def getEntryValue(event):
global entryVar, lableVar
x = entryVar.get() #get the value from Entry
x = int(x) #change it to an int
lableVar.set(x) #set the lable variable
entryVar.set("") #clear the entry variable
if __name__ == "__main__":
main()
So, what's going on here is that we make a window in the usual way. I've created both an Entry() widget to get some input, and a Label() widget to show whatever has been input. I've broken the Entry() and Label() declarations up over multiple lines just to make them easier to read.
You can attach variables to many TKinter widgets to that you can .get() and .set() their values more easily, but they almost always need to be TKinter variable types such as StringVar() or IntVar(). I've created two such variables, one for the Entry() widget and another for the Label() widget.
I've also added "bindings" to the Entry() widget to both show how that works and to make data entry a bit more convenient. I don't know if you have a separate number pad on your computer keyboard so I've bound both the main <enter> key as well as the number pad's <enter> key. When you hit either one of those keys, the Entry() widget will call the getEntryValue() function which does the work of getting the value and displaying it on the window.
For convenience, entry.focus_set() immediately puts the focus on the Entry() widget, then the TKinter window enters the .mainloop() to do its stuff.
The getEntryValue() function is called by the events which we set on the Entry() widget. I broke it down into more lines than necessary to illustrate what needs to happen. First we retrieve the value of the Entry() widget through its variable, entryVar. You do that using entryVar's .get() method: x = entryVar.get(). That returns a string value which you will have to convert to an integer using the normal int() function available in Python. For this purposes of this demonstration I've chosen to display that value to a Label() widget which I've placed in the window, so I use the Label() widget's variable lableVar: lableVar.set(x). You don't have to convert the integer back into a string before doing this.
I then clear out the entryVar variable so that there isn't anything left in the Entry() widget to get in the way of our next entry.
I've used entryVar and lableVar as globals just to simplify the example.
And that's how you do it.
I guess the problem is here:
a=str(e3.get())
Try something like this:
a=int(e3.get())
Since what you want is an integer

Python guizero: textBox = [textBox]

OK, I been using guizero for a couple of days but I found a problem that has been perplexing me. Here a simplified version of the code.
from guizero import App, Text, PushButton, Picture, Drawing, TextBox
app = App("Testing")
def test():
global testing
print(testing)
button = PushButton(app,test, text = "press to test")
button.bg = "red"
button.text_size= 35
tittle = Text(app, "Testing input here")
testing = TextBox(app, text= "" )
app.display()
No matter what the users input into the Textbox, it is always print:
[TextBox] object with text ""
I tried putting testing into an argument in the function test, it comes up with the same thing.
[TextBox] object with text ""
If I don't make an argument in the function or global testing, it makes the same thing, and if I make the textbox before the button, I have the same problem.
Can anyone find a way to work around the problem or to fix this, I'm new to guizero so I have little to an idea what I'm doing
If you want to print the contents of the Text widget then you need to do
def test():
global testing
print(testing.value)
This will get the value of the testing widget rather than the "repr" of the widget.
Seems like a bit of "bug" in guizero that the description text that is output doesn't update when the value of the widget is updated.
Issue has been accepted by the developer and a fix has been pushed to a development branch. https://github.com/lawsie/guizero/issues/392

Python, Tkinter: store content of Entry field into a variable

Dear fellow programmers,
I use Python 2.7 on windows 10 64 bits.
I have an issue with a Tkinter window. In a parent program, I want to save a file and I ask the name of the file in a Tkinter window. My problem is that I don't succeed to get this name outside of the Tkinter window. Here is the Python code:
from Tkinter import *
globalFilename = ""
class Master:
def __init__(self, top):
self.filename = ""
frame_e = Frame(top)
frame_e.pack()
self.t_filename = StringVar()
entry = Entry(frame_e, textvariable=self.t_filename, bg="white")
entry.pack()
entry.focus_force()
saveButton = Button(frame_e, text="Save", command=self.on_button)
saveButton.pack(side=BOTTOM, anchor=S)
def on_button(self):
self.filename = self.t_filename.get()
print self.filename
root.quit()
root.destroy()
root = Tk()
root.geometry("100x100+100+50")
M = Master(root)
print M.filename
root.mainloop( )
print M.filename
globalFilename = M.filename
print globalFilename
All print statements in this code give nothing when I enter any text into the Entry textbox. This is not what I expect. If I enter "test" I expect "test" to appear for each print statement (i. e. four times here). I tried to go everywhere on the Internet, I tried various tutorials, I tried to copy various examples, to follow various videos, I just don't succeed in fixing this issue.
Note that this piece of code is embedded into a function called saveGame, which is used in a pygame loop.
Thanks in advance! All the best!
Your code works.
The window is not drawn on the screen until you call mainloop(), so printing M.filename before that point prints an empty string (the initialization value). The mainloop() blocks until the window closes, after which 3 print statements successfully print the value that the user entered into the box.
You may be interested in the easygui module, which does exactly what your program does except you don't have to make it yourself.
Ok, as other posters told, the above code works in a vacuum. It did not work as embedded in my program because I initialized a duplicate tk() before calling my function and initialize it again. I removed this duplicate and it worked.

Elegant solution about class and referencing

I've recently started using classes in my programs and I've got 2 problems/questions.
Following the question I've pasted not the whole code, but only the part about which I need advise about.
1)the only way I have found to access to the value the user will input in my GUI's entry widget is to declare the list ac global, so I can later append the various entry widget for further reference. I tried it in my printer function and it worked. I was just wondering if there is another way to manage the problem because using a global variable, according to what I read on the net, is not the very best idea.
2)I've got some problem with doing the same thing with the optionwidget. I can't find a way to get the data because of variable referencing problems. Assuming that I'm managing this thing the best way an apprentice of Python could, how can I do that?
If I wasn't clear, please let me know. I'm not a native English speaker and I still have to get confidence with the language.
from tkinter import *
root = Tk ()
root.title("GENERATOR")
root.geometry("300x300")
class entryandlabel:
global ac
ac=[]
def printer():
#as an example
print(ac[2].get())
def createentry(lista):
#entry widget creation
i=1
for a in lista:
entry = Entry (root)
entry.grid(row=i, column=1, sticky = W)
ac.append(entry)
i+=1
def createoption(lista, c):
#option widget creation
a = StringVar(root)
a.set("Selezionare")
b = OptionMenu(*(root, a) + tuple(lista))
b.grid(row=c, column=1)

Python-Tkinter Text Insert not affecting box

First time poster, found the site very helpful before registering though.
I am having issues using Tkinter on Python 2.7 (Windows7):
The code (I have truncated it because the whole thing is massive) looks something like this:
-------------------------------------------------------
CODE:
#set up stuff, importing variables, etc, then we have:
class App:
global RXSerial
RXSerial=''
#The following lines define the topFrame, lays out the widgets.
def __init__(self, master):
topFrame = Frame(master)
topFrame.pack()
middleFrame = Frame(master)
middleFrame.pack()
#--------------defining state variables------------
self.inputConsole = Text(middleFrame)
self.inputConsole.insert(INSERT,"Data recieved from Serial:")
self.inputConsole.config(width=100,height=20)
self.inputConsole.pack(side=LEFT,padx=20,pady=20)
#blah blah blah, insert a bunch of stuff (buttons etc.) here:
#The following lines define the functions to be called when the buttons are pressed.
def engineFire(self,engineUse,pwm):
RXSerial='this should pop up in the text called inputConsole'
print RXSerial
self.inputConsole.insert(INSERT, RXSerial)
---------------------------------------------------
so yeah, basically RXSerial is a string (that I have checked that is working, the print RXSerial line successfully prints when called by a button. The problem is that the self.inputConsole.insert(INSERT,RXSerial) line is not working. Can anybody please help? I have tried a bunch of combinations of stuff but cant seem to get it working. Thank you.
If you're trying to insert the text from another thread it may fail to work. Also, if at some point you configured the text widget to be in the disabled state then inserting will fail. If that's the case (widget is disabled), setting the state to "normal" temporarily will solve the problem.
Without more information it's impossible to say for sure.

Categories

Resources