Please Help me. I'm running a simple python program that will display the data from mySQL database in a tkinter form...
from Tkinter import *
import MySQLdb
def button_click():
root.destroy()
root = Tk()
root.geometry("600x500+10+10")
root.title("Ariba")
myContainer = Frame(root)
myContainer.pack(side=TOP, expand=YES, fill=BOTH)
db = MySQLdb.connect ("localhost","root","","chocoholics")
s = "Select * from member"
cursor = db.cursor()
cursor.execute(s)
rows = cursor.fetchall()
x = rows[1][1] + " " + rows[1][2]
myLabel1 = Label(myContainer, text = x)
y = rows[2][1] + " " + rows[2][2]
myLabel2 = Label(myContainer, text = y)
btn = Button(myContainer, text = "Quit", command=button_click, height=1, width=6)
myLabel1.pack(side=TOP, expand=NO, fill=BOTH)
myLabel2.pack(side=TOP, expand=NO, fill=BOTH)
btn.pack(side=TOP, expand=YES, fill=NONE)
Thats the whole program....
The error was
x = rows[1][1] + " " + rows[1][2]
IndexError: tuple index out of range
y = rows[2][1] + " " + rows[2][2]
IndexError: tuple index out of range
Can anyone help me??? im new in python.
Thank you so much....
Probably one of the indices is wrong, either the inner one or the outer one.
I suspect you meant to say [0] where you said [1], and [1] where you said [2]. Indices are 0-based in Python.
A tuple consists of a number of values separated by commas. like
>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
tuple are index based (and also immutable) in Python.
Here in this case x = rows[1][1] + " " + rows[1][2] have only two index 0, 1 available but you are trying to access the 3rd index.
This is because your row variable/tuple does not contain any value for that index. You can try printing the whole list like print(row) and check how many indexes there exists.
I received the same error with
query = "INSERT INTO table(field1, field2,...) VALUES (%s,%s,...)"
but in the statement
cursor.execute(query, (field1, field2,..)
I had delivered less variables as necessary...
In this case I used
import mysql.connector as mysql
I just wanted to say that this is also possible...not only in arrays
(I didn't have a very close look at this specific case...)
Related
Query = search _entry.get()
Sql = *SELECT FROM customers where last_name = %s"
Data = (query,)
Result = my_cursor. Execute (sql, data)
Result = my_cursor. fetchall ()
If not result :
Result = "record not found... "
Query_label = Label(search _customer _window, text =result)
Query_label. Place (x=40,y=130)
else :
For index, x in enumerate (result) :
Num =0
Index +=2
For y in x:
Query_label = Label(search _customer_window, text=y)
Query_label.grid(row=index,column=num)
Num +=1
I set the value of index to 2 but nothing happens. Thanks for your help.
When I run the program, the label (query_lqbel) is shown at top left side of the window (row 0, column =0), how can I change the location of label. Its actually a label on which some data are shown.
I'm writing the code as mentioned below to display Table of 2. There must be "Space" shown Before & After "X" as " X " but instead I'm getting "{}". Seeking for Help as I'm new to programming.
Code:
import tkinter
table = tkinter.Tk()
table.geometry("280x420")
table.title("GUI Table Practice")
n = 2
for i in range(1, 11):
v = (n, ' X ', i, ' = ', n*i)
s = tkinter.Label(text=v, font="Times 20")
s.pack()
table.mainloop()
Result:
Try formatting instead of passing a tuple as text:
import tkinter
table = tkinter.Tk()
table.geometry("280x420")
table.title("GUI Table Practice")
n = 2
for i in range(1, 11):
s = tkinter.Label(text=f'{n} X {i} = {n*i}', font="Times 20")
s.pack()
table.mainloop()
I have defined a function here and it is supposed to work correctly because im using a similar function somewhere else but without giving any conditions(where.. like or regexp) and it works fine there, when i use regexp and all it does not give an output. Why is that? Thanks in advance :)
Code:
def search():
log = Toplevel(root)
log.title('View all customers')
def db():
selected = drop.get()
result_win = Toplevel(log)
result_win.title('Search result')
con = mysql.connect(host='localhost', user='root',
password='*****', database='BOOK')
c = con.cursor()
c.execute(f"SELECT * from books where '{selected}' regexp
'{e_sch.get()}';")
result = c.fetchall()
index=0
for index, x in enumerate(result):
num = 0
for y in x:
lookup_label = Label(result_win, text=y)
lookup_label.grid(row=index+1, column=num)
num +=1
con.close()
l1 = Label(result_win,text='Sl.No',font=font_text)
l2 = Label(result_win,text='Title',font=font_text)
l3 = Label(result_win,text='Authors',font=font_text)
l4 = Label(result_win,text='Subject',font=font_text)
l5 = Label(result_win,text='Availablity',font=font_text)
btn_ext = Button(result_win,text='Exit',font=font_text,command=result_win.destroy,borderwidth=2,fg='#eb4d4b')
l1.grid(row=0,column=0,padx=20)
l2.grid(row=0,column=1,padx=20)
l3.grid(row=0,column=2,padx=20)
l4.grid(row=0,column=3,padx=20)
l5.grid(row=0,column=4,padx=20)
btn_ext.grid(row=index+2,columnspan=7,ipadx=540)
global a
l = Label(log,text='Search',font=Font(family='helvetica', size='20'))
drop = ttk.Combobox(log,value=['Search by....','Sl.no','Title','Authors','Subject','Availablity'])
drop.current(0)
l2 = Label(log,text='Enter',font=font_text)
e_sch = Entry(log)
b_sch = Button(log, text='Search book', command=db, font=font_text)
b_ext = Button(log, text='Exit', command=log.destroy, font=font_text)
a = drop.get()
l.grid(row=0,columnspan=3,pady=20)
drop.grid(row=1,column=0,columnspan=3)
l2.grid(row=2,column=0,padx=(20,0))
e_sch.grid(row=2,column=1, padx=30, ipady=5,pady=20)
b_sch.grid(row=3,column=0,columnspan=3,ipadx=200)
b_ext.grid(row=4,column=0,columnspan=3,ipadx=237)
Sometimes i get this error too UnboundLocalError: local variable 'index' referenced before assignment
The syntax of the SELECT statement is incorrect:
SELECT * from books where '{selected}' regexp '{e_sch.get()}';
should be:
SELECT * from books where `{selected}` regexp '{e_sch.get()}';
Field name should be surrounded by ``, not ''.
I have been building a flashcard app and have run into a roadblock while trying to implement a radiobutton. The issue is when run the menu shows up and your able to access the lesson, but the radiobuttons do not appear. Whenever the code is run this error shows up TypeError: string indices must be integers attached to the radiobutton functionbalancing_radio_butto1 = Radiobutton(balancing_frame, text = balancing[answer_list[0]], variable=balancing_radio, value = 1) if someone could explain the why this error shows up as well as how to fix it it would be much appreciated. Below is my code that I have so far.
from tkinter import *
from PIL import ImageTk, Image
from random import branding
import random
root = Tk()
root.title('Chemistry Flashcards')
root.geometry("500x500")
def balancing():
balancing_frame.pack(fill="both", expand=1)
global show_balancing
show_balancing = Label(balancing_frame)
show_balancing.pack(pady=15)
global balancing
balancing = ['balanced1', 'balanced2', 'balanced3', 'balanced4', 'balanced5', 'unbalanced1', 'unbalanced2', 'unbalanced3', 'unbalanced4', 'unbalanced5']
global balancing_state
balancing_state = {
'balanced1':'balanced',
'balanced2':'balanced',
'balanced3':'balanced',
'balanced4':'balanced',
'balanced5':'balanced',
'unbalanced1':'unbalanced',
'unbalanced2':'unbalanced',
'unbalanced3':'unbalanced',
'unbalanced4':'unbalanced',
'unbalanced5':'unbalanced',
}
answer_list = []
count = 1
while count < 3:
rando = randint(0, len(balancing_state)-1)
if count == 1:
answer = balancing[rando]
global balancing_image
balancing = "C:/Users/Kisitu/Desktop/project/balancing/" + balancing[rando] + ".png"
balancing_image = ImageTk.PhotoImage(Image.open(balancing))
show_balancing.config(image=balancing_image)
answer_list.append(balancing[rando])
'''random.shuffle(balancing)'''
count += 1
random.shuffle(answer_list)
global balancing_radio
balancing_radio = IntVar()
balancing_radio_butto1 = Radiobutton(balancing_frame, text = balancing[answer_list[0]], variable=balancing_radio, value = 1)
balancing_radio_butto1.pack(pady=10)
balancing_radio_butto2 = Radiobutton(balancing_frame, text = balancing[answer_list[1]], variable=balancing_radio, value = 2).pack()
my_menu = Menu(root)
root.config(menu=my_menu, bg='#B7F7BB')
lesson_menu = Menu(my_menu)
my_menu.add_cascade(label="Lesson", menu=lesson_menu)
lesson_menu.add_command(label="balancing", command=balancing)
lesson_menu.add_separator()
lesson_menu.add_command(label="Exit", command=root.quit)
balancing_frame = Frame(root, width=500, height=500, )
root.mainloop()
... text = balancing[answer_list[0]] ...
balancing is a list, you are trying to index a value from the list.
you are passing answer_list[0] as index.
answer_list contains random strings from balancing.
you are trying to index a list with a string like in
balancing["balanced2"]
maybe you could use a dictionary?
I am workin with Python 2.7. This is the initial part of a longer programme. What I want to do is to add a new username, together with is height and weight. I use a .txt file to store user data,
example userlist3.txt:
add_new_user 1 1
unknown_user 170 70
monthy 185 83
[empty line]
This is the code:
from Tkinter import *
user_list = Tk()
user_list.title('Users')
def add_new_user():
global select
global height
global weight
select = name.get()
height = h.get()
weight = w.get()
f = ' '
us=open("userlist3.txt","a")
print name, height, weight
us.write(select + f + str(height) + f + str(weight) + "\n")
us.close()
# add_user.destroy() # it doesn't work
user_list.destroy()
def onSelect(ev): # (10)
global select
select=listb.get(listb.curselection()) # (12)
lab.configure(text=select) # (14)
global name
global h
global w
if select == 'add_new_user':
add_user = Tk()
add_user.title('New user')
a=Label(add_user,text="Your username").pack()
name = StringVar()
NAME = Entry(add_user,textvariable = name).pack()
b=Label(add_user,text="Your height (in cm)").pack()
h = IntVar()
H = Entry(add_user,textvariable = h).pack()
c=Label(add_user,text="Your weight (in kg)").pack()
w = IntVar()
W = Entry(add_user,textvariable = w).pack()
Add_New_User=Button(add_user,text="Add new user data",command=add_new_user).pack()
add_user.mainloop()
else:
user_list.destroy()
a=open("userlist3.txt","r")
b =[]
for linea in a:
b.append(linea)
a.close()
e = []
for i in range(len(b)):
e.append(b[i].split())
userlist = []
heightlist = []
weightlist = []
for i in range(len(e)):
userlist.append(e[i][0])
heightlist.append(e[i][1])
weightlist.append(e[i][2])
sbar = Scrollbar(user_list, orient=VERTICAL) # (20)
listb = Listbox(user_list, width=30, height=4) # (22)
sbar.config(command=listb.yview) # (30)
listb.config(yscrollcommand=sbar.set) # (32)
sbar.pack(side=RIGHT, fill=Y) # (40)
listb.pack() # (42)
lab=Label(user_list,text="Double Click on User") # (50)
lab.pack()
for c in userlist: listb.insert(END,c)
listb.bind('<Double-1>',onSelect) # (70)
user_list.mainloop()
for d in range(1,len(userlist)):
if userlist[d] == select:
height = int(heightlist[d])
weight = int(weightlist[d])
print "Selected user is: ",select
print height
print weight
It works with user already present in the txt file, but not if I want to add a new one. When I try, I got 'PY_VAR0 0 0' printed on the shell and '' 0 0 added in a new line in the txt file. Obviously these data are of no use in the following steps of my software.I'm probably missing a .get() somewhere.
When you see something like PY_VAR0, that means you are printing out the instance of a StringVar (or IntVar or whatever), rather than printing out the value of the variable. If you are using one of the special vars, you must call the get() method to get the value.
In your specific case, change this:
print name, width, height
To this:
print name.get(), width, height
Thanks Fiver for your advice!
metaphy's solution works, I solved the problem modifying line 28 in
add_user = Toplevel(user_list)