How do I display the output of a MySQL query with TKinter?
Code Snippet:
cursor.execute("SELECT bin FROM stock_lists WHERE part_number = %s", (myvar))
self.myvar=cursor.fetchone()
self.label4 = Label(self, text=0, textvariable=self.myvar)
The snippet code above should display the bin value in the self.label4 widget. But currently the label is not displaying anything. What am I doing wrong?
You have to ways to resolve your problem:
First option:
First, if you want to keep the use of a Tkinter variable as you did, you need to modify its content using the set() method:
#You must declare your Tkinter variable previously in your code:
self.tkinter_variable = StringVar()
# Then modify your last line of code this way:
self.label4 = Label(self, textvariable=self.tkinter_variable.set(self.myvar))
Second option:
An other option is to use the text option correctly and get rid of textvariable option especially if you do not need it to control the labels using a Tkinter variable. This means that you need to change this line:
self.label4 = Label(self, text=0, textvariable=self.myvar)
To:
self.label4 = Label(self, text=self.myvar)
Related
I'm using python 2.7 with Tkinter (new to Tkinter:))
I have UI with list of 20 checkboxes
once I click on one checkbox, all checkboxes are being checked, instead of one.
In code below you'll see 2 line (once with #)
with # -when click on checkbox only one is checked which is ok
without # -when click on one, all are being checked
The problem is that I want to know the status of each checkbox if checed or not and I have to define var=Intvar in order to "get" it status
Any suggestion?
Thanks in advance
Below is relevant def
def suites_checkbox_create(self):
ExcelWorkBook1 = open_workbook(config.UI_Suites_Location + 'STD_SUITES.xlsx', on_demand=True)
First_Sheet1 = ExcelWorkBook1.sheet_by_index(0)
plushight = 110
suitesList=[]
self.CheckboxList=[]
for name in (First_Sheet1._cell_values):
if name[3] == "General Name":
continue
else:
suitesList.append(name[3])
for index, name in enumerate(suitesList):
self.var=IntVar
#self.CheckboxList.append(Checkbutton(self.app, text=name)) # using this, i can check once checkbox a time
self.CheckboxList.append(Checkbutton(self.app, text=name, variable=self.var)) # with this, once i check once checkbox, all checkboxes(20) are bing checked
self.CheckboxList[index].place(y=plushight)
plushight += 20
The reason this happens is because you've given all of your Checkbutton widgets the same variable for their variable attribute.
Meaning that as soon as one of the Checkbutton widgets is ticked self.var is given a value of 1 which means that all of the Checkbutton widgets have a value of 1 which equates to them having been selected.
In short, whenever one is ticked it updates the value of all the other's because they have the same variable used to store their value.
See this in the example below:
from tkinter import *
root = Tk()
var = IntVar()
for i in range(10):
Checkbutton(root, text="Option "+str(i), variable = var).pack()
root.mainloop()
To resolve this you need to use a different variable for each Checkbutton, like the below:
from tkinter import *
root = Tk()
var = []
for i in range(10):
var.append(IntVar())
Checkbutton(root, text="Option "+str(i), variable = var[i]).pack()
root.mainloop()
This question is about programming in Python 2.7.x
I wanted to code a programme where there are two functions exist: one of those is a method to get input from the user, and the other one is to show the input. Both are supposed to be done in GUI. Let's call the first function as GET TEXT function, and the second as SHOW TEXT function; my strategy is to open a GUI, show a text box, and put a button to go to SHOW TEXT function. Then, the first line of the SHOW TEXT function is to close the window opened by the GET TEXT function, get the value of the input text, and print it in another GUI.
So, I tried doing this,
from Tkinter import *
import tkMessageBox
def texttobeenteredhere():
application = Tk()
textbox = Text(application)
textbox.pack()
submitbutton = Button(application, text="OK", command=showinputtext)
submitbutton.pack()
application.mainloop()
def showinputtext():
application.quit()
thetext = textbox.get()
print "You typed", thetext
texttobeenteredhere()
I got errors that I could not comprehend, but I hope you get my idea even though my explanation could be really bad. Please suggest a solution to my problem, where the GET TEXT function and SHOW TEXT function have to exist separately in the code.
EDIT:
Thanks Josselin for introducing the syntax class in python. What I actually wanted to say was, I want the programme to open a window to get input from the user, and then close the window, and finally open another window to show the input text. I am honestly new to this, but through my prior knowledge and guessing, I tried to modify the code to meet my expectation.
import Tkinter as tk
global passtext
class application(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.textbox = tk.Text(self)
self.textbox.pack()
self.submitbutton = tk.Button(self, text="OK", command=self.showinputtext)
self.submitbutton.pack()
self.mainloop()
def showinputtext(self):
self.thetext = self.textbox.get("1.0", "end-1c")
print "You typed:", self.thetext
self.destroy()
class showtext(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.setthetext = tk.StringVar()
self.setthetext.set(passtext)
self.showthetext = tk.Label(self, textvariable=self.setthetext)
self.showthetext.pack()
self.submitbutton = tk.Button(self, text="OK", command=self.destroy)
self.submitbutton.pack()
self.mainloop()
# Launch the GUI
app = application()
# Access the entered text after closing the GUI
passtext = app.thetext
text = showtext()
My English can sometimes be not understandable, but this question is answered. Thank you very much.
There are 2 main problems in your code:
First, in your showinputtext function, you want to access elements of your GUI, but they are not defined within the scope of the function.
Second, when reading the content of a tk.Text widget, the .get() method takes 2 arguments (see this link).
To fix the first problem, the best is to define your application as a class, with an inner function taking the class instance self as input argument, such that application widgets can be called within the function.
Code:
import Tkinter as tk
class application(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.textbox = tk.Text(self)
self.textbox.pack()
self.submitbutton = tk.Button(self, text="OK", command=self.showinputtext)
self.submitbutton.pack()
self.mainloop()
def showinputtext(self):
self.thetext = self.textbox.get("1.0", "end-1c")
print "You typed:", self.thetext
self.destroy()
# Launch the GUI
app = application()
# Access the entered text after closing the GUI
print "you entered:", app.thetext
I've been trying to store it as a single string, let alone appending it to a list, by making a variable for it called "Whatisthisthing", but it's not working. Also, do you know why I can't use "Whatisthisthing" to replace Entry.get() with defining Showoncanvas?
import Tkinter
import random
master = Tkinter.Tk()
Entry = Tkinter.Entry()
Entry.pack()
Whatisthisthing = Entry.get()
Canvas = Tkinter.Canvas()
Canvas.pack()
def Showoncanvas(event):
Canvas.create_text(random.randint(10,100), random.randint(10,100), anchor = "center", text=Entry.get())
Entry.bind("<Return>", Showoncanvas)
print Whatisthisthing
master.mainloop()
An entry widget has an textvariable option in which the current text / content is stored. If you use a StringVar as the textvariable the content is automatically synched with this variable and can be read using StringVar's .get() method.
Since I do not have Python 2.7 installed on my system, I converted your code to Python 3 and used mentioned StringVar and its .get() method:
#!/usr/bin/env python3
# coding: utf-8
import tkinter
import random
master = tkinter.Tk()
Whatisthisthing = tkinter.StringVar()
Entry = tkinter.Entry(textvariable=Whatisthisthing)
Entry.pack()
Canvas = tkinter.Canvas()
Canvas.pack()
def Showoncanvas(event):
Canvas.create_text(random.randint(10,100), random.randint(10,100), anchor="center", text=Whatisthisthing.get())
Entry.bind("<Return>", Showoncanvas)
print(Whatisthisthing.get())
master.mainloop()
The only differences between Python 2 and Python 3 should be the following:
Tkinter --> tkinter
print --> print()
I am new to Python and Qt4 and am running into some problems with taking user entered/selected information and then using them as arguments for other python files. Here's the two situations & code:
Users enter an ID # into a lineEdit box, and on button click, program will run a script with the ID # entered as an argument. e.g., ID # = 11503, on button click: programname.py 11503 will run. This sort of works, but puts spaces between each number in the ID and I don't know if it's the cleanest way to do what I want.
ID # process button SIGNAL:
QtCore.QObject.connect(self.ui.pushButton_2, QtCore.SIGNAL('clicked()'), self.processID)
SIGNAL calls this:
def processID(self):
import subprocess
from PyQt4 import QtCore, QtGui
rawID = (self.ui.lineEdit.text())
idList = []
for x in rawID:
idList.append(str(x))
subprocess.call(["Python" "programname.py"] + idList, shell=True)
Pretty much the same situation as above, but one of the arguments needed for the "programname.py" script is a file directory. I have a comboBox populating with the names of the directories, but can't get it to take the selection and print it as an argument. Here's the code for that:
Combobox Directory population
import glob, os
myList = sorted(glob.glob('C:\\Python27\\test_directories\\*'))
new_myList = []
for x in myList:
new_myList.append(os.path.basename(x))
self.ui.comboBox_4.addItems(new_myList)
Directory combobox SIGNAL
self.ui.comboBox_4.activated[str].connect(self.Directory)
I connected a different button to the comboBox and tried to replicate what I did with the lineEdit, but it just won't work at all. However, I CAN print the user selection with the code below, so it's functional, just not in the way I want.
Directory comboBox selection print test
def Directory(self, item):
print(item)
Any help would be greatly appreciated. (And if you make it all the way through this long post, thank you!)
I am making a GUI in Tkinter that has the user input information and writes it to an excel via openpyxl. I have a few OptionMenu widgets in there and I want to be able to save whatever the user selects from the dropdown menu to a variable that I can then write to a file.
Here is what I have so far:
self.equipment = StringVar(top)
self.equipment.set("10077")
self.e18 = OptionMenu(top, self.equipment,'10077','G2143','G2145','17727')
self.e18.grid(row=13, column=1, sticky=E+W)
Later, in another function I assign it to a variable:
equipment = self.equipment
I then write it to a file:
ws1['D18'] = str(equipment)
When I open the file, instead of the user selected string showing up in the cell, this does: PY_VAR16
All the other information entered in Entryboxes write to excel perfectly. Anybody know how to save the OptionMenu selection to a string so that it will write to excel? Is there an equivalent of a .get() command for this widget? Thanks in advance
Is there an equivalent of a .get() command for this widget?
According to this page, StringVars do indeed have a get method. I suggest replacing
ws1['D18'] = str(equipment)
With
ws1['D18'] = equipment.get()