from tkinter import *
import tkinter as tk
q = 0
s = -1
count = 0
correct = 0
incorrect = 0
question = ["Is this a quiz","Are you sure","Dont be","see its not a quiz"]
answer = ["yes","yes","ok","ok"]
answer_cap = ["Yes","Yes","Ok","Ok"]
root = Tk()
name = tk.Label(root,text = "GUI Quiz")
name.pack()
label = tk.Label(root,text = question[0])
label.pack()
entry = tk.Entry(root)
entry.pack()
def out():
global q,correct,incorrect,s,count
count = count + 1
ans = entry.get()
print (ans)
print (question[q])
print (answer[q])
if count < 4:
if answer[q] or answer_cap[q] == ans :
q = q + 1
entry.delete(0, END)
correct = correct + 1
label.config(text = question[q])
else:
q = q + 1
entry.delete(0, END)
incorrect = incorrect + 1
label.config(text = question[q])
else:
entry.delete(0, END)
label.config(text = "Correct: "+str(correct) + " Incorrect: "+str(incorrect))
def stop():
global q,correct,incorrect
q = 0
correct = 0
incorrect = 0
entry.delete(0, END)
label.config(text = question[0])
button = tk.Button(root,text = "Submit",command = out)
button.pack()
button_two = tk.Button(root,text = "Restart",command = stop)
button_two.pack()
root.mainloop()
nothing actually wrong with the code its just how I'm doing it. When I run module it will ask my four questions and I will give the answer, but no matter what I put it will say I got 3 correct and none wrong. Am I missing something obvious or is it how I layed out the code.
The first part of your out function should not have 'count = count + 1' because this adds one to you score regardless of weather you were right or wrong; relocate the commented code.
def out():
global q,correct,incorrect,s,count
#count = count + 1
ans = entry.get()
print (ans)
print (question[q])
print (answer[q])
Related
I'm attempting to develop a registration form, but I can't get the value of the entries because nonetype and return self func are specified.
I tried entering values into the entries, but nothing worked. Again, we find that understanding some of the features and structure of your code is required before you can make modifications.
import tkinter as tk
from tkinter import *
from tkinter import ttk
class App():
# created window
# made all entries global
##################################################### ENTRIES #####################################################################
# some entries
def submit():
MsgBox = messagebox.askokcancel('FYEF',"stuff",icon = 'info')
if MsgBox == True:
# ENTRIES
enroll = enroll_code.get()
readonly = readonly_combo.get()
school = schools.get()
sc_did = sc_id.get()
sc_dd = sc_add.get()
vr = vrb.get()
if vr == 1:
vr = 'Private'
elif vrb == 2:
vr = 'Public'
PSA = PSA_no.get()
lr_no = lr_number.get()
last_nme = last_name.get()
first_nme = first_name.get()
mid_nme = mid_name.get()
ext_nme = ext_name.get()
birth_dte = birth_date.get()
ageyr = age.get()
vhr = vhar.get()
if vhr == 1:
vhr = 'Male'
elif vhr == 2:
vhr = 'Female'
iic = ip_ic.get()
if iic == 1:
iic = 'Yes'
elif iic == 2:
iic = 'No'
mother_ton = mother_tongue.get()
relgaff = relg_aff.get()
spneeds = sp_needs.get()
eadd = em_add.get()
hom_add = home_add.get()
f_name = fath_name.get()
f_contact = fath_contact.get()
m_name = moth_name.get()
m_contact = moth_contact.get()
g_name = guar_name.get()
g_contact = guar_contact.get()
m_wifi = means_wifi.get()
p_modal = pref_modal.get()
concern = concerns.get()
approve = approval.get()
tday = date.today()
dte = today.strftime("%B %d, %Y")
woot = tk.Tk()
wlc = ttk.Label(woot, text='🎊Welcome!', font='bold, 30').place(x=50,y=100)
# SUBMIT Button
submit_button = ttk.Button(tab_2, text="Submit", command=submit).place(x=655,y=700)
App()
Edit: Asked by Delrius Euphoria. The woot = tk.Tk(), app = App(), and woot.mainloop() should be outside of class . ttk.Label should be outside of function
Try this:
import tkinter as tk
from tkinter import *
from tkinter import ttk
woot = tk.Tk()
class App():
# created window
# made all entries global
##################################################### ENTRIES #####################################################################
# some entries
def submit():
MsgBox = messagebox.askokcancel('FYEF',"stuff",icon = 'info')
if MsgBox == True:
# ENTRIES
enroll = enroll_code.get()
readonly = readonly_combo.get()
school = schools.get()
sc_did = sc_id.get()
sc_dd = sc_add.get()
vr = vrb.get()
if vr == 1:
vr = 'Private'
elif vrb == 2:
vr = 'Public'
PSA = PSA_no.get()
lr_no = lr_number.get()
last_nme = last_name.get()
first_nme = first_name.get()
mid_nme = mid_name.get()
ext_nme = ext_name.get()
birth_dte = birth_date.get()
ageyr = age.get()
vhr = vhar.get()
if vhr == 1:
vhr = 'Male'
elif vhr == 2:
vhr = 'Female'
iic = ip_ic.get()
if iic == 1:
iic = 'Yes'
elif iic == 2:
iic = 'No'
mother_ton = mother_tongue.get()
relgaff = relg_aff.get()
spneeds = sp_needs.get()
eadd = em_add.get()
hom_add = home_add.get()
f_name = fath_name.get()
f_contact = fath_contact.get()
m_name = moth_name.get()
m_contact = moth_contact.get()
g_name = guar_name.get()
g_contact = guar_contact.get()
m_wifi = means_wifi.get()
p_modal = pref_modal.get()
concern = concerns.get()
approve = approval.get()
tday = date.today()
dte = today.strftime("%B %d, %Y")
wlc = ttk.Label(woot, text='🎊Welcome!', font='bold, 30').place(x=50,y=100)
enroll_code =ttk.Entry(woot).place(x=50,y=150)
# SUBMIT Button
submit_button = ttk.Button(woot, text="Submit", command=submit).place(x=655,y=700)
app = App()
woot.mainloop()
I need to count the number of clicks on two buttons and then a percentage list
I have a problem with passing str (self.counter)
to 3 functions which are to divide one function by another and show it as a percentage result
self.counter = 0
def clicked():
self.counter += 1
L['text'] = 'Poprawnie: ' + str(self.counter)
self.counter2 = 0
def clicked2():
self.counter2 += 1
R['text'] = 'Niepoprawnie: ' + str(self.counter2)
def clickedSum():
a_number = str(self.counter) / str(self.counter2)
percentage = "{:.2%}".format(a_number)
print(percentage)
If this is part of a class (as it has self reference, I assume it to be), you might have to initiate your two counters in the init to avoid they will be class-variables instead of instance-variables.
like so:
def __init__(self, *args, **kwargs):
self.counter = 0
...
def clicked():
...
ok, I managed to write, I will leave it if someone has a similar problem;)
self.counter = 0
self.counter2 = 0
def clicked():
self.counter += 1
L['text'] = 'True: ' + str(self.counter)
def clicked2():
self.counter2 += 1
R['text'] = 'False: ' + str(self.counter2)
def clicked3():
S['text'] = 'All click: ' + str(self.counter / (self.counter2 + self.counter)) + '%'
S = Label(self, text="All:0%")
S.pack()
b = Button(self, text="True", padx=35, pady=10, fg="#ffffff", bg="#263942", command=lambda: [clicked(), clicked3()])
b.pack(side="right")
L = Label(self, text="True:0")
L.pack(side="right")
b2 = Button(self, text="False", padx=35, pady=10, fg="#ffffff", bg="#263942", command=lambda: [clicked2(), clicked3()])
b2.pack(side="left")
R = Label(self, text="False:0")
R.pack(side="left")
Tic-tac-toe game using python tkinter is not working correctly.
Tic-tac-toe structure is correct. I just want to change the click event.
Only button9 output shown when click to any button
Every time I click any button this output is shown
from tkinter import *
bclick = True
tk = Tk()
tk.title("Tic Tac toe")
tk.geometry("300x400")
n = 9
btns = []
def ttt(button):
global bclick
print(button)
if button["text"] == "" and bclick == True:
print("if")
button.config(text="X")
bclick = False
elif button["text"] == "" and bclick == False:
print("else")
button["text"] = "0"
bclick = True
for i in range(9):
btns.append(Button(font=('Times 20 bold'), bg='white', fg='black', height=2, width=4))
row = 1
column = 0
index = 1
print(btns)
buttons = StringVar()
for i in btns:
i.grid(row=row, column=column)
i.config(command=lambda: ttt(i))
print(i, i["command"])
column += 1
if index % 3 == 0:
row += 1
column = 0
index += 1
tk.mainloop()
Common misstake. The lambda function is using the last value assigned to i so every lambda will use i=.!button9. change the lambda function to:
i.config(command=lambda current_button=i: ttt(current_button))
which will make lambda use the value of i when the lambda was created.
I am trying to create the GUI code for my connect four boardgame but error's keep on coming up that I don't know how to correct. Can anyone help? The error:
TypeError: init() missing 1 required positional argument: 'buttns_list'
Code:
def __init__(self):
self.mw = tkinter.Tk()
self.mw.title = ("Connect Four")
self.rows = 6
self.cols = 7
self.buttons_2d_list = []
for i in range (self.rows):
self.rows = ['']*self.cols
self.buttons_2d_list.append(self.rows)
self.gboard = ConnectFourBoard()
p1 = HumanPlayer("X")
p2 = ComputerPlayer("O", self.buttns_list)
self.players_1st = (p1, p2)
self.currnt_player_index = 0
self.winner = False
def clicked_btn(self, x, y):
p = self.players_1st[self.currnt_player_index]
button = self.buttons_2d_list[x][y]
if button["text"] == "":
button["text"] = p.get_player_symbol()
self.gboard.MakeMove(x, y, p.get_player_symbol())
winner = self.gboard.CheckForWin()
is_full = self.gboard.FullBoard()
if winner == True:
win_message = ("Player %s is the winner!" %p.get_player_symbol())
messagebox.showinfo("Winner Info", win_messge)
self.mw.destroy()
exit()
elif is_full == True:
messagebox.showinfo("Winner Info", "The game is a draw")
self.mw.destroy()
exit()
else:
pass
if self.currnt_player_index == 1:
self.currnt_player_index = 0
else:
self.currnt_player_index += 1
p = self.players_1st[self.currnt_player_index]
p.play()
import random
class ComputerPlayer(Player):
def __init__(self, letter, buttns_list):
Player.__init__(self, letter)
self.buttons_2d_list = buttns_list
def play(self):
pass
It's not clear to me from the rest of the code exactly what you should be passing here, but your init calls for a letter, which you do have, and a buttns_list, which you don't:
def __init__(self, letter, buttns_list):
So the error comes from this line:
p2 = ComputerPlayer("O")
Either:
1) Pass in a buttns_list if your ComputerPlayer class needs it
p2 = ComputerPlayer("O", self.buttons_2d_list)` # in GameGUI init
2) Get rid of it if this was added by mistake:
class ComputerPlayer(Player):
def __init__(self, letter):
Player.__init__(self, letter)
if option == "1":
with open("sample.txt","r") as f:
print(f.read())
numbers = []
with open("sample2.txt","r") as f:
for i in range(9):
numbers.append(f.readline().strip())
print(numbers)
from random import randint
for i in range(9):
print(numbers[randint(0,8)])
from tkinter import *
def mhello():
mtext = ment.get()
mLabel2 = Label(test, text=mtext).pack()
return
test = Tk()
ment = StringVar()
test.geometry('450x450+500+10')
test.title('Test')
mlabel = Label(test, text='Time to guess').pack()
mbutton = Button(test, text='Click', command = mhello).pack()
mEntry = Entry(test, textvariable=ment).pack()
test.mainloop()
from tkinter import *
def mhello():
my_word = 'HELLO'
mtext = ment.get()
if my_word == mtext:
mLabel2 = Label(test, text='Correct').pack()
else:
mLabel2 = Label(test, text='Incorrect').pack()
return
test = Tk()
ment = StringVar()
test.geometry('450x450+500+300')
test.title('Test')
def label_1():
label_1 = Label(test, text='Hello. Welcome to my game.').pack()
def label_2():
label_2 = Label(test, text='What word am I thinking of?').pack()
button_1 = Button(test, text='Click', command = mhello).pack()
entry_1 = Entry(test, textvariable=ment).pack()
label_1()
test.after(5000, label_2)
test.mainloop()
from tkinter import *
from random import shuffle
game = Tk()
game.geometry('200x200')
game.grid()
game.title("My Game")
board = [1, 2, 3, 4, 5, 6, 7, 8, 9]
def board_1():
board1 = []
k = 0
for i in range(3):
for j in range(3):
board1.append(Label(game, text = board[k]))
board1[k].grid(row = i, column = j)
k +=1
def board_2():
shuffle(board)
board2 = []
k = 0
for i in range(3):
for j in range(3):
board2.append(Label(game, text = board[k]))
board2[k].grid(row = i, column = j)
k +=1
board_1()
game.after(5000, board_2)
game.mainloop()
#2nd Option
elif option == "2":
print ("You have chosen option 2. Well Done, You Can Type! XD")
The bit that has the Syntax Error is the 1st elif statement (2nd Option). Ignore all the code prior to this if necessary (it is there for context). Whenever I run the code it says that there is a syntax error and just positions the typing line (I don't know what it's called) at the end of the word elif.
This is a simple fix, with if else statements you need to have a closing ELSE and in this case there is not so when your program runs it sees that theres a lonely if without its else :)
if option == "1":
elif option == "2":
else:
'do something else in the program if any other value was recieved'
also a switch statement can be used here so it does not keep checking each condition and just goes straight to the correct case :D
The problem is that your block is separated from the first if-statement, where it actually belongs to. As it is, it follows the game.mainloop() statement, and adds an unexpected indentation. Try to rearrange your code like so:
if option == "1":
with open("sample.txt","r") as f:
print(f.read())
numbers = []
with open("sample2.txt","r") as f:
for i in range(9):
numbers.append(f.readline().strip())
print(numbers)
from random import randint
for i in range(9):
print(numbers[randint(0,8)])
elif option == "2":
print ("You have chosen option 2. Well Done, You Can Type! XD")
[ Rest of the code ]