How do I refresh an image on TKinter - python

My function mapupdater isn't working. It seems tkinter isn't keeping a reference to the image. I tried storing the reference in an array, I tried what was suggester here How to update the image of a Tkinter Label widget?
Both don't work.
#-----Begin Global Declarations-----#
global futureonoff
futureonoff = True
#-----End Global Declarations-----#
#Create a new window
window = Tkinter.Tk()
window.wm_title("SpaceMass")
window.geometry("1000x1000")
window.self= Text(bg='black')
window.self.pack(fill="both", expand=True)
#updating map based on ISS location
def mapupdater():
global futureonoff
marker_list = []
timenowforcomputing = strftime("%Y-%m-%d %H:%M:%S", gmtime())
iss.compute(timenowforcomputing)
currentlong = iss.sublong
currentlat = iss.sublat
currentlongfloat= float(iss.sublong)
currentlatfloat= float(iss.sublat)
#convert radians to degrees with the equations 1 radian = 57.2957795 degrees
#TODO Learn how to use pi in python
currentlongfloat = round(currentlongfloat*57.2957795, 3)
currentlatfloat= round(currentlatfloat*57.2957795, 3)
print(currentlongfloat)
print(currentlatfloat)
if futureonoff == True:
futureintermenter = 0
while futureintermenter < len(long_list_3_orbits):
marker_list.append("markers=size:mid|label:F|color:blue|"+str(lat_list_3_orbits[futureintermenter])+","+str(long_list_3_orbits[futureintermenter])+"|")
futureintermenter = futureintermenter + 1
marker_list.append("markers=size:mid|label:S|color:red|"+str(currentlatfloat)+","+str(currentlongfloat)+"|")
toopenupdater = get_static_google_map("mymap2", center="42.950827,-122.108974", zoom=1, imgsize=(500,500), imgformat="gif", maptype="satellite", markers=marker_list)
#Code from https://stackoverflow.com/questions/6086262/python-3-how-to-retrieve-an-image-from-the-web-and-display-in-a-gui-using-tkint
uupdater = urllib.urlopen(toopenupdater)
raw_data_u = uupdater.read()
u.close()
b64_data_u = base64.encodestring(raw_data_u)
imgtoprint = Tkinter.PhotoImage(data=b64_data)
# from http://www.daniweb.com/software-development/python/threads/79337/putting-an-image-into-a-tkinter-thingy
# pick an image file you have .bmp .jpg .gif. .png
# load the file and covert it to a Tkinter image object
panel1.configure(image = imgtoprint)
panel1.image = imgtoprint
#updata map after 30 seconds
window.after(30000, mapupdater)
def togglemap():
global futureonoff
print(futureonoff)
if futureonoff == True:
futureonoff = False
else:
futureonoff = True
mapupdater()
print(futureonoff)
#text_file.configure(text=testing)
#Info about buttons http://effbot.org/tkinterbook/button.htm
#Parsing code from https://stackoverflow.com/questions/773797/updating-tkinter-labels-in-python
#settings for font, font size, pixel size, of the text in our GUI
#convert radians to degrees with the equations 1 radian = 57.2957795 degrees
#TODO Learn how to use pi in python
currentlongfloat = round(currentlongfloat*57.2957795, 3)
currentlatfloat= round(currentlatfloat*57.2957795, 3)
if futureonoff == True:
futureintermenter = 0
while futureintermenter < len(long_list_3_orbits):
marker_list.append("markers=size:mid|label:F|color:blue|"+str(lat_list_3_orbits[futureintermenter])+","+str(long_list_3_orbits[futureintermenter])+"|")
futureintermenter = futureintermenter + 1
marker_list.append("markers=size:mid|label:S|color:red|"+str(currentlatfloat)+","+str(currentlongfloat)+"|")
#places map into GUI
toopen = get_static_google_map("mymap2", center="42.950827,-122.108974", zoom=1, imgsize=(500,500), imgformat="gif", maptype="satellite", markers=marker_list)
#im = PIL.Image.open("mymap2.png")
#imageFile = "mymap2.png"
#Code from https://stackoverflow.com/questions/6086262/python-3-how-to-retrieve-an-image-from-the-web-and-display-in-a-gui-using-tkint
#print(toopen)
u = urllib.urlopen(toopen)
raw_data = u.read()
u.close()
b64_data = base64.encodestring(raw_data)
global imgtoprint
imgtoprint = Tkinter.PhotoImage(data=b64_data)
panel1 = Tkinter.Label(window, image=imgtoprint, bg='black')
panel1.pack(side='top', fill='both', expand='yes')
panel1.place(x=250, y=115)
b = Button(window, text="Browse for XML File", font=("Helvetica", 15), command=fileback, bg = 'black')
b.pack()
b.place(x=425,y=650)
c = Button(window, text="Toggle Orbit Prediction on Map", font=("Helvetica", 15), command=togglemap, bg = 'black')
c.pack()
c.place(x=425,y=850)
mapupdater()
window.mainloop()

Related

Windows serial port timing issue or bad code? [Python]

I am writing an application for a digital lab balance that connects over serial. To build the application I set up a COM port bridge and wrote a program to simulate the balance on my machine (the balance was in use). I will show you the most recent version of the balance simulation program:
import serial, random, time
s = serial.Serial('COM2')
#Initially we will just push a random float
#After the data the scale sends a carraige return + line feed
def pushData():
data = f'{round(random.uniform(10, 100), 2)}\r\n'.encode()
print(f'Sending Data: {data}')
s.write(data)
try:
while True:
pushData()
time.sleep(10)
except:
print('Something went wrong.')
This code along with my balance application works as expected on my machine. But when I try to use my balance program with the actual device it does not get all the serial data if it even works at all. I am wondering if I need some kind of multi-threading, if its a timing issue or something. I know the balance works because I can monitor the COM port.
I will post my most recent balance program here:
# !/usr/bin/python3
################ Imports
import serial, pyperclip
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from datetime import datetime, time
from tkinter import *
################ Declarations
GUI = Tk()
s = serial.Serial('COM5', timeout=1)
wgtList = [0,0,0,0,0]
wgtDict = {'Lab':[],
'Weight':[]}
newL = '\r\n'
tareWgt = 0
newWgt = 0 #Trying to get past program not working when no data is pushed
################ Functions
def thisAfter():
"""Updates scale feed and updates the scale feed."""
try:
global newWgt
newWgt = float(s.readline().decode().rstrip('\r\n')) - tareWgt
except ValueError:
#print('ValueError thisAfter(): NO DATA OR COULD NOT CONVERT SERIAL DATA TO FLOAT')
print('ValueError thisAfter(): '+ str(newWgt))
print('wgtList: '+ str(wgtList))
wgtList.append(newWgt)
if newWgt not in wgtList[0:5]:
text.insert(INSERT,str(newWgt)+newL)
if len(wgtList) > 5:
del wgtList[0]
GUI.after(50, thisAfter)
text.see(END)
def labCallback():
"""Saves data to file, iterates the entry field."""
num = labEntry.get()
csvStr = datetime.today().strftime("%Y/%m/%d") + ',' + datetime.now().strftime("%H:%M:%S") + ',' + num + ',' + str(wgtList[-1]) + ',' + var1.get() + ',' + str(tareWgt) + newL
with open('data.csv', 'a+', newline = '') as file:
if file.readline() == None:
file.write('Date, Time, Lab, Weight, Type' + newL)
file.write(csvStr)
#print(csvStr) #Just checking
labEntry.delete(0,END)
labEntry.insert(0, int(num) + 1)
csvArr = csvStr.split(',')
wgtDict['Lab'].append(int(csvArr[2]))
wgtDict['Weight'].append(float(csvArr[3]))
text2.insert(INSERT, ',\t'.join(csvArr))
text2.see(END)
#print(str(wgtDict)+'\n')
def tareCallback():
global tareWgt
tareWgt = wgtList[-1]
print(tareWgt)
text3.insert(INSERT,newL+str(tareWgt))
text3.see(END)
def copyData():
global newWgt
pyperclip.copy(newWgt)
def close():
s.close()
def start():
global s
try:
s = serial.Serial('COM5', timeout=1)
thisAfter()
except:
print('Serial port closed')
################ Frames/Panes
frame1 = LabelFrame(GUI, text = 'Lab Label + Entry Field')
frame1.pack(side = TOP)
frame6 = LabelFrame(frame1, text = 'Tare')
frame6.pack(side = BOTTOM)
frame2 = LabelFrame(GUI, text = 'Scale Feed')
frame2.pack(side = BOTTOM)
frame3 = LabelFrame(GUI, text = 'Saved Feed')
frame3.pack(side = BOTTOM)
frame4 = LabelFrame(GUI, text = 'Plot')
frame4.pack(side = TOP)
frame5 = LabelFrame(frame1, text = 'Type Select')
frame5.pack(side = BOTTOM)
################ Lab Label + Entry Field + Type Select
labLabel = Label(frame1, bd = 5, text = 'Lab#')
labLabel.pack(side = LEFT)
tareLabel = Label(frame6, bd = 5, text = 'Tare')
tareLabel.pack(side = LEFT)
text3 = Text(frame6, height = 1, width = 20)
text3.pack(side = RIGHT)
closeButton = Button(frame1, text = 'Close', command = close)
closeButton.pack(side = RIGHT)
startButton = Button(frame1, text = 'Start', command = start)
startButton.pack(side = RIGHT)
tareButton = Button(frame1, text = 'Tare', command = tareCallback)
tareButton.pack(side = RIGHT)
undoButton = Button(frame1, text = 'Undo')
undoButton.pack(side = RIGHT)
labButton = Button(frame1, text = 'Save', command = labCallback)
labButton.pack(side = RIGHT)
copyButton = Button(frame1, text = 'Copy', command = copyData)
copyButton.pack(side = RIGHT)
labEntry = Entry(frame1)
labEntry.pack(side = RIGHT)
var1 = StringVar()
r1 = Radiobutton(frame5, text = 'pH', variable= var1, value = 'pH')
r1.pack(anchor = 's')
r2 = Radiobutton(frame5, text = 'pH-Tray', variable= var1, value = 'pH-Tray')
r2.pack(anchor = 's')
r3 = Radiobutton(frame5, text = 'Mehlich', variable= var1, value = 'Mehlich')
r3.pack(anchor = 's')
r4 = Radiobutton(frame5, text = 'Nitrate', variable= var1, value = 'Nitrate')
r4.pack(anchor = 's')
r5 = Radiobutton(frame5, text = 'Excel', variable= var1, value = 'Excel')
r5.pack(anchor = 's')
r6 = Radiobutton(frame5, text = 'Excel-Tray', variable= var1, value = 'Excel-Tray', state=DISABLED)
r6.pack(anchor = 's')
r1.select()
r2.deselect()
r3.deselect()
r4.deselect()
r5.deselect()
r6.deselect()
################ Scale Feed
scrollbar = Scrollbar(frame2)
scrollbar.pack(side = RIGHT, fill = Y)
text = Text(frame2, yscrollcommand = scrollbar.set, height = 10)
text.pack()
text.bind('<ButtonPress>', lambda e: 'break')
scrollbar.config(command = text.yview)
#thisAfter()
################ Saved Feed
scrollbar = Scrollbar(frame3)
scrollbar.pack(side = RIGHT, fill = Y)
text2 = Text(frame3, yscrollcommand = scrollbar.set, height = 10)
text2.pack()
scrollbar.config(command = text.yview)
################ Plot
f = plt.Figure(dpi=50, figsize=(13, 4))
plt.xkcd()
a = f.add_subplot(111)
def animate(i):
xL = wgtDict['Lab']
yL = wgtDict['Weight']
a.clear()
a.plot(xL, yL)
canvas = FigureCanvasTkAgg(f, frame4)
canvas.get_tk_widget().pack(side = LEFT, fill = BOTH)
ani = animation.FuncAnimation(f, animate, interval=1000)
# This is some kind of 'while true' loop fyi
GUI.mainloop()

How to change color of a special frame in Tkinter TTK? [duplicate]

This question already has answers here:
Setting background color of a tkinter ttk frame
(3 answers)
Closed 3 years ago.
I want to change the background of my ttk form (ceasar code script) to the color I have in my window = #FEFB22
I want to change the white "box" color to #FEFB22 click to see image !
from tkinter import *
from tkinter import ttk
# variables
letters="ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ"
# fenetre
root = Tk()
#window title
root.title('Cesar Crypt/Decrypt par Maxence')
root.iconbitmap("logo.ico")
# allows for window to be resized
root.geometry("850x480")
# window background
root.configure(background='#FEFB22')
root.frame_header = ttk.Frame()
ttk.Label(root.frame_header, text = 'Code César', style = 'Header.TLabel').grid(row = 0, column = 1)
ttk.Label(root.frame_header, text = 'Entrez un nombre entre 1 et 25 :', style = 'Header.TLabel').grid(row = 1, column = 0)
ttk.Label(root.frame_header, text = 'Votre Message:', style = 'Header.TLabel').grid(row = 2, column = 0)
ttk.Label(root.frame_header, text='Votre message crypté/decrypté:',style='Header.TLabel').grid(row=4, column=0)
enc_dec_text = ttk.Entry(root.frame_header, width=110)
enc_dec_text.grid(row=4,column=1)
cipher_shift_menu = StringVar()
Spinbox(root.frame_header,from_=1, to=25, textvariable=cipher_shift_menu).grid(row=1, column=1)
text_entry = ttk.Entry(root.frame_header, width=100)
text_entry.grid(row=2,column=1)
def encrypt_text():
stringtoencrypt = text_entry.get()
stringtoencrypt = str(stringtoencrypt)
stringtoencrypt=stringtoencrypt.upper()
ciphershift = cipher_shift_menu.get()
ciphershift=int(ciphershift)
stringencrypted=""
for character in stringtoencrypt:
position = letters.find(character)
newposition = position+ciphershift
if character in letters:
stringencrypted = stringencrypted + letters[newposition]
else:
stringencrypted = stringencrypted + character
enc_dec_text.insert(0, stringencrypted)
def decrypt_text():
stringtodecrypt = text_entry.get()
stringtodecrypt = str(stringtodecrypt)
stringtodecrypt=stringtodecrypt.upper()
ciphershift = cipher_shift_menu.get()
ciphershift=int(ciphershift)
stringdecrypted=""
for character in stringtodecrypt:
position = letters.find(character)
newposition = position-ciphershift
if character in letters:
stringdecrypted = stringdecrypted + letters[newposition]
else:
stringdecrypted = stringdecrypted + character
enc_dec_text.insert(0, stringdecrypted)
#add image
width = 200
lenght = 200
image = PhotoImage(file="logort.png")
#bouton image
button = Button(root, image=image, bg='#FEFB22', bd=0, relief=SUNKEN)
button.pack()
# boutous
encrypt_button = ttk.Button(root.frame_header,text='Encrypter',command = lambda: encrypt_text()).grid(row=3,column=0)
decrypt_button = ttk.Button(root.frame_header,text='Decrypter',command = lambda: decrypt_text()).grid(row=3,column=1)
#bouton q
# uitter
bouton_quitter = Button(root, text="Quitter !", command=root.quit, font=("Courrier", 20), bg='#000000', fg='#FEFB22')
bouton_quitter.pack(side=BOTTOM)
root.frame_header.pack()
root.mainloop()
You can use ttk.Style to change the frame background color:
s = ttk.Style()
s.configure('My.TFrame', background='#FEFB22')
root.frame_header = ttk.Frame(root, style='My.TFrame')

How to have different actions happen every second and then repeat every four seconds

My title may be kind of confusing, but I essentially want to draw a different set of shapes every four seconds then start over. For example, second one I want to draw triangles, second two I want to draw lines, second three I want to draws rectangles, and second four I want to draw ovals. The for second five I want this process to repeat. My Idea was to use the remainder which works up to second seven. Also is this possible to do without importing any additional modules. Any help would be great and if something was not clear please ask.
Thanks,
Scott
Here is my current code to run if you want:
from tkinter import *
from random import *
#creates a class
class mainWindow():
def __init__(self,theWindow,winName):
#Sets values for variable
self.running = 0
#makes theWindow and instnace var
self.theWindow = theWindow
#creates the main frames
self.mainFrame = Frame(theWindow,width=600,height=200,bg="light gray")
self.secondframe = Frame(theWindow,width=600, height =287, bg = "green")
self.mainFrame.grid()
self.secondframe.grid()
# gives the window a title
theWindow.title(winName)
# do not resize window based on widgets
self.mainFrame.grid_propagate(False)
# window location
theWindow.geometry('+500+300')
#Makes it so the window wont resize
self.theWindow.resizable(0,0)
#
self.theWindow.wm_attributes("-topmost",1)
`enter code here`#Creates the three frames that will be used
#Inerts a blank label to help with formating
self.blank1 = Label(self.mainFrame, bg= "light gray", height =3, width=19)
self.blank1.grid(row=0, column=0, rowspan =1)
#Creates and places the start button
self.startbutton = Label(self.mainFrame,text = "Start", bg= "green", height =1, width=10,relief=RAISED)
self.startbutton.bind("<Button-1>", self.startTimer)
self.startbutton.grid(row=0, column=2, rowspan =1, sticky = E)
#Creates and places the stop button
self.stopbutton = Label(self.mainFrame,text = "Stop", bg= "red", height =1, width=10,relief=RAISED)
self.stopbutton.bind("<Button-1>", self.endTimer)
self.stopbutton.grid(row=0, column=3, rowspan =1, sticky =W)
#Creates and places the timer
self.timerLabel = Label(self.mainFrame,text = "Time: 0", bg= "white", height =2, width=14,relief=SUNKEN)
self.timerLabel.bind("<Button-1>",)
self.timerLabel.grid(row=3, column=2, columnspan =2, pady =25)
#draws the canvas
self.drawCanvas = Canvas(self.secondframe,width=598,height=285, bg= "light green")
self.drawCanvas.grid()
#Function for strting the timer
def startTimer(self,event):
if self.running == 0:
self.running = 1
self.countElapse(0)
#function for ening the timer
def endTimer(self,event):
if self.running == 1:
self.running = 0
self.timecount = 0
self.drawCanvas.delete(ALL)
self.timerLabel.configure(text = "Time: %d" %0)
#function for showing the time
def countElapse(self,localTime = NONE):
#self.timerLabel.configure()
if self.running:
if localTime is not NONE:
self.timecount = localTime
self.timerLabel.configure(text ="Time: "+str(self.timecount+1))
self.timecount = self.timecount+1
self.drawshapes(self.timecount)
self.mainFrame.after(1000,self.countElapse)
#function for drawing the shpaes
def drawshapes(self,timecount):
self.drawCanvas.delete(ALL)
color = ["red","white","purple","green","lime green", "cyan", "black","light blue","blue","pink","brown","gray"]
numshapes = 100
counter = 0
print(self.timecount)
var = self.timecount
#draws ovals
if var % 4 ==0:
while counter != numshapes:
counter += 1
x = randint(10,600)
y = randint(10,600)
x1 = randint(10,600)
y1 = randint(10,600)
#draws the shape
self.drawCanvas.create_oval(x,y,x1,y1,fill=choice(color))
#draws rectangles
elif var % 3 ==0:
while counter != numshapes:
counter += 1
x = randint(10,600)
y = randint(10,600)
x1 = randint(10,600)
y1 = randint(10,600)
self.drawCanvas.create_rectangle(x,y,x1,y1,fill= choice(color))
#draws Lines
elif var % 2 ==0:
while counter != numshapes:
counter += 1
x = randint(10,600)
y = randint(10,600)
x1 = randint(10,600)
y1 = randint(10,600)
self.drawCanvas.create_line(x,y,x1,y1,fill= choice(color))
#draws triangles
elif var % 1 ==0:
while counter != numshapes:
counter += 1
x = randint(10,600)
y = randint(10,600)
x1 = randint(10,600)
y1 = randint(10,600)
x2 = randint(10,600)
y2 = randint(10,600)
self.drawCanvas.create_polygon(x,y,x1,y1,x2,y2,fill= choice(color))
def main():
# create a tkinter object
mainWin = Tk()
# create a mainWindow object
theMainWin = mainWindow(mainWin,"Scott Rodgers")
# keep the window displaying
mainWin.mainloop()
#calls main
main()
What you are looking for is how to use the .after method.
Here is how it works.
Lbl = Label()
Lbl.pack()
Lbl.after([Amount of milliseconds], lamba: [Function])
For more advanced notation,
after(delay_ms, callback=None, *args)
What this does is that it registers an alarm callback that is called after a given time

Is there a way to write superscripts in python in a GUI?

This is my current code and it displays in a window but literally prints it the way I've typed it (obviously). But is there a way to write these so they are displayed as powers/exponents?
"
questionNum = 0
#SET QUESTIONS HERE
questions = [0,"Given that y = x^4 + 6x^1/2, find dy/dx","Write down the value of 125^1/3","Fully factorise 9x^2 - 25","Find the value of 8^5/3"]
answer1 = [0,"4x^4 + 3x^1/2","25","(3x-5)(3x+5)","1/2"]
answer2 = [0,"4x^3 + 6x^1/2","1/5","(3x+5)(3x+5)","Answer 2 (4)"]
answer3 = [0,"4x^3 + 6x^-1/2","5","(3x-5)(3x-5)","Answer 3 (4)"]
answer4 = [0,"4x^3 + 1/2x^-3/2","125","(9x+5)(x-5)","Answer 4 (4)"]
This is what it looks like:
rightanswers = [0,1,2,3,4] #These are the correct answers
"
This is the bit that needs to be changed. I've added the rest just in case you need any of it to see what's going on:
from tkinter import * #The TKinter module imported in order to create the menus
import sys #Invoke functions and statements - allows operations to work and searches for named modules i.e. TKinter
global questionNum #Connections between functinos and arrays
questionNum = 0
#SET QUESTIONS HERE
questions = [0,"Given that y = x^4 + 6x^1/2, find dy/dx","Write down the value of 125^1/3","Fully factorise 9x^2 - 25","Find the value of 8^5/3"] #This is the question bank which has been set up as an array
answer1 = [0,"4x^4 + 3x^1/2","25","(3x-5)(3x+5)","1/2"] #These are the possible answers - this is where multiple choice answers would go
answer2 = [0,"4x^3 + 6x^1/2","1/5","(3x+5)(3x+5)","Answer 2 (4)"]
answer3 = [0,"4x^3 + 6x^-1/2","5","(3x-5)(3x-5)","Answer 3 (4)"]
answer4 = [0,"4x^3 + 1/2x^-3/2","125","(9x+5)(x-5)","Answer 4 (4)"]
rightanswers = [0,1,2,3,4] #These are the correct answers
normal = Tk() #Build the TKinter
normal.geometry("850x350") #Set the size of the normal chess form to 850x350
normal.title("Normal Chess") #Sets a title for the normal chess form
normal.columnconfigure(1,minsize = 300) #This is whereabouts the question and answers are displayed
questionVar = StringVar() #Question will be a string
answerVar = IntVar() #Answers will be numbers
answerVar.set(1) #Questions can only have one solution
aText = StringVar() #Text for the answers - options
bText = StringVar()
cText = StringVar()
dText = StringVar()
qNoText = StringVar() #Questions text which is displayed to the user
questionText = StringVar()
normal.withdraw() #Allows the user to only select one option
title = Tk() #Builds the TKinter
title.title("Chess") #Title of the form
title.geometry("300x300") #The size of the image
watermark = PhotoImage(file = "watermark.gif") #Link to the image itself
Label(image = watermark).place(x=0,y=0,relwidth=1,relheight=1) #Places the image onto the form set on the x,y coordinates
title.withdraw()
menu = Tk() #Builds the TKinter
menu.title("Main Menu") #Displays 'Main Menu' on screen
menu.geometry("400x350") #Size of the form
p1var = StringVar() #Sets a variable for Player 1 and Player 2
p2var = StringVar()
def Quit(): #Quit function - allows the user to exit the program
menu.destroy()
title.destroy()
normal.destroy()
sys.exit() #Gets rid of all the modules
def play():
title.deiconify()
Label(title,text = "Enter Details:",font = ("Calibri",25)).grid(row = 1, column = 1)
#'Enter Details' font, size and location on the form
Label(title,text = "CHESS",font = ("Calibri",50)).grid(row = 0,column = 1)
#'CHESS' font, size and location on the form
Label(title, text = "Player 1: ").grid(row = 2,column = 0)
#'Player 1' font, size and location on the form
Entry(title,textvariable = p1var,width = 30).grid(row = 2,column = 1)
#Allows the user to input a string for the player 1 name
Label(title, text = "Player 2: ").grid(row = 3,column = 0)
#'Player 2' font, size and location on the form
Entry(title,textvariable = p2var,width = 30).grid(row = 3,column = 1)
#Allows the user to input a string for the player 2 name
Label(title,text = "Select Game Mode: ").grid(row = 4,column = 1)
#'Select Game Mode: ' font, size and location on the form
Button(title,command = lambda: playNormalChess(p1var.get(),p2var.get()),text = "Normal Chess").grid(row = 6,column = 1,sticky = W)
#Button for normal chess
Button(title,command = lambda: playSpeedChess(p1var.get(),p2var.get()),text = "Speed Chess").grid(row = 6,column = 1,sticky = E)
#Button for speed chess
Button(title,command = instructions,text = "Instructions").grid(row = 7,column = 1,pady =10)
#Button for instructions
def playNormalChess(p1,p2):
normal.deiconify()
t = Label(textvariable = qNoText,font = ("Arial",50)).grid(row = 0,column = 1,sticky = W,columnspan=2,padx = 20,pady =10)
#Functions for selection
q =Label(textvariable = questionVar,font = ("Arial",30)).grid(row = 1,column = 1,sticky = W,columnspan=2,padx = 20,pady =10)
#Font and size the questions are set in
a=Radiobutton(variable = answerVar,value = 1,textvariable = aText,font = ("Arial",18)).grid(row = 3,column = 1,pady =5,padx = 20,sticky = W)
#These are the radio buttons which are linked to the answers - set the font and the size of the text
b=Radiobutton(variable = answerVar,value = 2,textvariable = bText,font = ("Arial",18)).grid(row = 4,column = 1,padx = 20,sticky = W)
c=Radiobutton(variable = answerVar,value = 3,textvariable = cText,font = ("Arial",18)).grid(row =5,column = 1,pady = 5,padx = 20,sticky = W)
d=Radiobutton(variable = answerVar,value=4,textvariable = dText,font = ("Arial",18)).grid(row = 6,column = 1,padx = 20,sticky = W)
Button(text = "Submit",command = confirm).grid(row =0,column = 3,sticky = W,pady = 10) #Submit button to confirm their answers
newQuestion() #Calls the function for a new question
def confirm():
if messagebox.askyesno('Confirm','Are You Sure?'): #This is the conformation of the correct answer for the user
try:
if answerVar.get() == rightanswers[questionNum]: #If they select yes to confirm they are happy with the selection
# - it checks their answer with the correct answer and prints 'Right' or 'Wrong' depending on their answer
print("Right")
else:
print("Wrong")
newQuestion() #Once their question is answered, a new question will be presented to them
except IndexError:
print("No more Questions")
def newQuestion():
global questionNum
questionNum = questionNum + 1
try:
qNoText.set("Question "+str(questionNum))
aText.set(answer1[questionNum])
bText.set(answer2[questionNum])
cText.set(answer3[questionNum])
dText.set(answer4[questionNum])
questionVar.set(questions[questionNum])
except IndexError:
print("No more questions")
Label(menu,text = "AS Maths Chess",font = ("Arial",37)).pack(pady = 20)
Button(menu,text = "Play",background = "black",foreground = "white",font = ("Arial",20),command = play).pack(ipadx = 80,ipady = 20, pady = 10)
Button(menu,text = "Quit",font = ("Arial",20),command = Quit).pack(ipadx = 80,ipady = 20, pady = 10)
Unicode has superscript numerals, arithmetic operators, and some letters in the BMP, which is supported by tcl/tk. See Wikipedia. Within those constraints, and given a supporting font, the answer is yes. On Windows, running from IDLE, the following works nicely and looks nice, though I would want the tk font larger to see the superscript easily with my eyes.
import tkinter as tk
root = tk.Tk()
# "4x^4 + 3x^1/2"
t1 = "4x\u2074 + 3x\u207b\u00b2" # \u excapes, if needed
t2 = "4x⁴ + 3x⁻²"
label = tk.Label(root, text=t2)
label.pack()

How to make simple GUI graph with Linear Equation

I am a beginner programmer. I have a task to make a GUI with a linear equation y=mx+b and a set of parameters where I can change the m and b values. I have both matplotlib and numpy. I also have tkinter for the GUI. This is what i have so far i edited my friends code on a coordinate GUI.
def onButtonValChange():
if X1.get() != '':
x[0] = float(X1.get())
if Y1.get() != '':
y[0] = float(Y1.get()
def createGraph(x,y):
graphRoot = Tk.Tk()
graphRoot.wm_title("Your Graph")
graphRoot.resizable(0,0)
f = Figure(figsize=(5, 4), dpi=100)
a = f.add_subplot(111)
a.plot(x, y)
canvas = FigureCanvasTkAgg(f, master=graphRoot)
canvas.show()
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
x = [1]
y = [1]
ButtonChangeValues = Tk.Button(root, text="Submit Change", command=onButtonValChange)
ButtonChangeValues.grid(row=11, columnspan=3)
ButtonCreateGraph = Tk.Button(root, text="Create This Graph", command=lambda: createGraph(x, y))
ButtonCreateGraph.grid(row="15", columnspan=3)
Tk.mainloop()
So here is some code that i use its a moving line graph but you could adapt the code to move only when you change the equation. all you would have to do is populate the lists of x0Coords y0Coords and xy0Coords with the right mx+b formula
# Run from IDLE or LXTerminal not IDLE 3
# for import spidev to work, must run as python (v2) not python3
from Tkinter import * #to run on python 2, use Tkinter, for python3 use tkinter
import math
from datetime import datetime, timedelta
import numpy as np
import spidev
#--------------------- variables -------------------------
#---user defined settings
screenWidth = 450
resolution = 5 #number of pixels between data points, for visual purposes only
samplePeriod = 100 #milliseconds, time between data points written to txt file
timeRange = .5 #minutes
#---end user settings
baseTime = int(timeRange*60*1000/screenWidth)
startTime = datetime.now()
nl = "\n"
root = Tk()
root.title("Simple GUI")
root.geometry("500x300") #widthxheight
C = Canvas(root, bg = "gray", height = 250, width = screenWidth)
x0Coords = []
y0Coords = []
xy0Coords = []
coordLength = int(screenWidth/resolution)
#---initiation of lists
for i in range(0,coordLength):
x0Coords.append(i*resolution)
y0Coords.append(125)
xy0Coords.append(0)
xy0Coords.append(0)
#putting X and Y corrdinites in a list
def coordinate():
global x0Coords, y0Coords, xy0Coords
for i in range(0,coordLength*2,2):
xy0Coords[i] = x0Coords[i/2]
xy0Coords[i+1] = y0Coords[i/2]
#print(xy0Coords)
#---End initiation of lists
c0 = C.create_rectangle(0,0,20,50)
cl0 = C.create_line(xy0Coords)
pressure = Label(root, text="test")
pressure.pack()
spi_0 = spidev.SpiDev()
spi_0.open(0, 0)
#--------------------------- End of Variables -------------------------
#--------------------------- Definitions ------------------------------
#shifts y values down in index in array to represent time moved forward
def shiftCoords(nextValue):
global y0Coords, xy0Coords
y0Coords.pop(0)
y0Coords.append(nextValue)
coordinate()
#updates the GUI based on the new time
def move_time():
global c0,cl0,xy0Coords, resolution, baseTime
C.delete(c0)
C.delete(cl0)
c0 = C.create_rectangle(0,0,20,int(float(readadc_0(0))/1023*250))
shiftCoords(125-int(float(readadc_0(0))/1023*125))
cl0 = C.create_line(xy0Coords)
#print(float(readadc_0(0))/1023*250)
root.title("V= " + str(round(3.3*float(readadc_0(0))/1023,2)))
root.after(baseTime*resolution,move_time)
C.pack()
root.after(baseTime,move_time)
root.after(samplePeriod,writeData)
root.mainloop()

Categories

Resources