I'm currently working on a project and when my program launches it needs to get the names off of two players before beginning, the way my program is at the moment, it is possible to press submit without entering names, how do I prevent this?
Many Thanks Jayode18
# Program by Jack O'Donnell (Jayode18 StackOverflow/GitHub)
# Date Started: 16th March 2019
# Import winsound and create functions for each of the sound effects & their functionalities.
import tkinter
import time
from tkinter import *
import random
import winsound
def gameOver():
winsound.PlaySound("Gameover", winsound.SND_FILENAME)
def pointsDrop():
winsound.PlaySound("Points drop", winsound.SND_FILENAME)
def pointsGain():
winsound.PlaySound("Points gain", winsound.SND_FILENAME)
def flipCoin():
winsound.PlaySound("coinflip", winsound.SND_FILENAME)
def rollDice():
winsound.PlaySound("Dice", winsound.SND_FILENAME)
# Other Definitions #
def goToPrimary():
primaryWindow = tkinter.Tk()
primaryWindow.iconbitmap("icon.ico")
primaryWindow.geometry("500x500")
primaryWindow.title("YGO Calculator ver. 1.0 ALPHA")
gainLPButton = Button(primaryWindow, text = "LP Gain", command = pointsGain)
gainLPButton.grid(row = 2, column = 1)
loseLPButton = Button(primaryWindow, text = "LP Loss", command = pointsDrop)
loseLPButton.grid(row = 2, column = 2)
gameOverButton = Button(primaryWindow, text = "LP = 0", command = gameOver)
gameOverButton.grid(row = 2, column = 3)
flipCoinButton = Button(primaryWindow, text = "Coin Toss", command = flipCoin)
flipCoinButton.grid(row = 2, column = 4)
rollDiceButton = Button(primaryWindow, text = "Roll Dice", command = rollDice)
rollDiceButton.grid(row = 2, column = 5)
# Button Commands #
def OnSubmit():
e = entry_duelist.get()
print(e)
time.sleep(0.25)
window.destroy()
goToPrimary()
# import tkinter and create the window window, then populate it with buttons to text window.
window = tkinter.Tk()
window.resizable(width = False, height = False)
window.title("YGO Calculator ver. 1.0 ALPHA")
window.iconbitmap('icon.ico') # Give window the correct icon
mainWindow = Frame(window)
window.geometry("180x75")
label_duelist = Label(mainWindow, text="Duelist 1:")
label_duelist_2 = Label(mainWindow, text="Duelist 2:")
entry_duelist = Entry(mainWindow)
entry_duelist_2 = Entry(mainWindow)
label_duelist.grid(row = 4, column = 0)
label_duelist_2.grid(row = 5, column = 0)
entry_duelist.grid(row = 4, column = 1, columnspan = 4)
entry_duelist_2.grid(row = 5, column = 1, columnspan = 4)
submit_button = Button(mainWindow, text = "Submit", command = OnSubmit)
submit_button.grid(row = 7, column = 4, columnspan = 2)
mainWindow.grid(row = 5, column = 0)
window.mainloop()
All help would be amazing, thanks again! :D
Thank you everyone for your help. I managed to find a working solution!
You can check the entry texts for example
if entry1.get() != "" And entry2.get() != "":
# entries are not empty, do something
Related
I couldnt seem to find a way to make my program realise that ive selected a button, so i changed the function of the celcius to farenheit to try to make it change a boolean value to determine what conversion the program is doing
def celcius_to_farenheit(_event = None):
c_to_f = True
f_to_c = False
the idea being later i can use if statments later in the end result function to find what conversion its doing and display results in the status bar
def end_result():
if c_to_f == True:
converted_temperature = (valid_temperature * 9/5) + 32
label_status.configure(text = converted_temperature, fg = "Orange")
currently i seem to have functions running without me pressing buttons as well, when start the program it immediatly goes to the error message ive created for input muct be numeric even if i havent pressed the celcius to farenheit button.
Any help regarding how to propely have my celcius to farenheit and farenheit to celcius buttons confirm its a float and change a value to use for determining which calculation its using would be helpfull. Knowing why the error message comes up automatically is a bonus.
Below is my code thank you for your time and help.
import sys
from tkinter import *
from tkinter.tix import *
c_to_f = True
def clear_reset(_event = None):
entry_temperature.delete(0, END)
label_status.configure(text = "All data cleared", fg = "Orange")
def end_program(_event = None):
sys.exit()
def convert_temp(_event = None):
try:
valid_temperature = float(entry_temperature.get())
except:
label_status.configure(text = "Input must be numeric", fg = "Orange")
def end_result():
if c_to_f == True:
converted_temperature = (valid_temperature * 9/5) + 32
label_status.configure(text = converted_temperature, fg = "Orange")
def celcius_to_farenheit(_event = None):
c_to_f = True
f_to_c = False
def farenheit_to_celcius(_event = None):
f_to_c = True
c_to_f = False
window = Tk()
window.geometry("550x200")
window.resizable(False, False)
window.title("Temperature Conversion")
tooltip = Balloon(window)
label_input_Temperature = Label(text = "Temperature",fg = "Green")
label_input_Temperature.grid(row= 0, column=0)
entry_temperature = Entry(window, bg = "light blue" )
entry_temperature.grid(row=0, column=1)
temp_button_c_to_f = Button(window, text = "Celcius to Farenheit", command = celcius_to_farenheit)
temp_button_c_to_f.grid(row = 1, column=0)
window.bind('<Shift-c>', celcius_to_farenheit)
tooltip.bind_widget(temp_button_c_to_f, msg = "Shift + C")
temp_button_f_to_c = Button(window, text = "Farenheit to Celcius")
temp_button_f_to_c.grid(row = 1, column = 1 )
conversion_button = Button(window, text = "Convert", command = convert_temp)
conversion_button.grid(row = 2, column = 0,padx =0 )
window.bind('<Enter>', convert_temp)
tooltip.bind_widget(conversion_button, msg = "Enter")
clear_button = Button(window, text = "Clear", command = clear_reset)
clear_button.grid(row = 2, column = 1)
window.bind('<Control-c>', clear_reset)
tooltip.bind_widget(clear_button, msg = "Ctrl + C")
exit_button = Button(window, text = "Exit")
exit_button.grid(row = 2, column = 2, padx = 20, pady = 20)
window.bind('<Control-x>', end_program)
tooltip.bind_widget(exit_button, msg = "Ctrl + X")
label_status = Label(window, width = 50, borderwidth = 2, relief= RIDGE,bg= "Grey" )
label_status.grid(row = 4, column = 1)
tooltip.bind_widget(label_status, msg = "Displays results / error messages")
label_status.configure(text = "Enter in your temperature and select your conversion", fg = "Orange")
window.mainloop()
I wrote a script for the Collatz Conjecture within a Tkinter GUI and displaying a Matplotlib graph of the result of the algorithm. Everything works OK except, the graph displays perfectly but then stops the script without populating the data field which displays the data points on which the graph is based. Only when I close the graph does is the data field populated.
I'm sure I'm doing something wrong in the script (probably indents) but I've tried everything but can't make it work. The script is added below:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from tkinter import *
from tkinter import messagebox
root=Tk()
root.title("Collatz Conjecture")
import matplotlib.pyplot as plt
import textwrap
from IPython import get_ipython
# sget_ipython().run_line_magic('matplotlib', 'qt')
#import matplotlib.backends.tkagg as tkagg
#from matplotlib.backends.backend_agg import FigureCanvasAgg
# Functions
lst = []
def collatz(num):
lst.clear()
while num != 1:
lst.append(num)
if num % 2 == 0:
num = int(num / 2)
else:
num = int(3 * num + 1)
def main(event):
num = int(input.get())
collatz(num)
plt.plot(lst)
plt.show()
output1.delete(1.0, END)
output1.insert(END, lst)
output2.delete(1.0, END)
output2.insert(END, "Number of iterations: " + str(len(lst)))
lbl1 = Label(root, width = 20, text = "Type in number\n & press Enter")
lbl1.grid(row = 1, column = 0, sticky = W)
lbl2 = Label(root, width = 40, text = "THE COLLATZ CONJECTURE")
lbl2.grid(row = 4, column = 0)
input = Entry(root, width = 20, bg = "light grey")
input.grid(row = 1, padx = 6, sticky = E)
input.get()
input.bind("<Return>", main)
canv = Canvas(root, width= 350, height= 350, bg = "white")
canv.grid(row = 6, column = 0, padx = (5,5), pady = (5,5))
img = PhotoImage(file = "/Users/andrehuman/Desktop/collatz_conjecture.png") # Tip to get full path: pull file into terminal!
canv.create_image(25, 25, image = img, anchor = NW)
bt1 = Button(root, width = 10, text = "About")
bt1.grid(row = 7, column = 0, pady = (5,7))
output1 = Text(root, wrap = WORD, width = 50, height = 7, bg = "light grey") # Note word wrap attribute
output1.grid(row = 3, column = 0, padx = (5,1), sticky = W)
output2 = Text(root, width = 50, height = 1, bg = "white")
output2.grid(row = 2, column = 0, sticky = W)
def about():
messagebox.showinfo("About", "The Collatz conjecture states that if you pick any positive whole number, and if its even, you divide it by two and if its odd, you multiply it by three and add one, and if you repeat this procedure often enough, the number that you started with will eventually reduce to one and if you play this game for long enough, your friends will eventually stop calling to see if you want to hang out ")
btn1 = Button(root, text = "About", command = about)
btn1.grid(row = 7, column = 0, pady = (5,7))
root.mainloop()
Any help would be appreciated.
Andre
PS, I'm not a professional coder or student coder as such... I'm doing this as a hobby and to inform myself about coding.
I am new in creating GUI. I am doing it in Python with Tkinter. In my program I calculate following characteristics
def my_myfunction():
my code ...
print("Centroid:", centroid_x, centroid_y)
print("Area:", area)
print("Angle:", angle)
I would like to ask for any help/tips how to display those values in GUI window or how to save them in .txt file so that I can call them in my GUI
Thanks in advance
Tkinter is easy and an easy way to do a GUI, but sometimes it can be frustrating. But you should have read the docs before.
However, you can do in this way.
from tkinter import *
yourData = "My text here"
root = Tk()
frame = Frame(root, width=100, height=100)
frame.pack()
lab = Label(frame,text=yourData)
lab.pack()
root.mainloop()
There are several ways to display the results of any operation in tkiner.
You can use Label, Entry, Text, or even pop up messages boxes. There are some other options but these will probably be what you are looking for.
Take a look at the below example.
I have a simple adding program that will take 2 numbers and add them together. It will display the results in each kind of field you can use as an output in tkinter.
import tkinter as tk
from tkinter import messagebox
class App(tk.Frame):
def __init__(self, master):
self.master = master
lbl1 = tk.Label(self.master, text = "Enter 2 numbers to be added \ntogether and click submit")
lbl1.grid(row = 0, column = 0, columnspan = 3)
self.entry1 = tk.Entry(self.master, width = 5)
self.entry1.grid(row = 1, column = 0)
self.lbl2 = tk.Label(self.master, text = "+")
self.lbl2.grid(row = 1, column = 1)
self.entry2 = tk.Entry(self.master, width = 5)
self.entry2.grid(row = 1, column = 2)
btn1 = tk.Button(self.master, text = "Submit", command = self.add_numbers)
btn1.grid(row = 2, column = 1)
self.lbl3 = tk.Label(self.master, text = "Sum = ")
self.lbl3.grid(row = 3, column = 1)
self.entry3 = tk.Entry(self.master, width = 10)
self.entry3.grid(row = 4, column = 1)
self.text1 = tk.Text(self.master, height = 1, width = 10)
self.text1.grid(row = 5, column = 1)
def add_numbers(self):
x = self.entry1.get()
y = self.entry2.get()
if x != "" and y != "":
sumxy = int(x) + int(y)
self.lbl3.config(text = "Sum = {}".format(sumxy))
self.entry3.delete(0, "end")
self.entry3.insert(0, sumxy)
self.text1.delete(1.0, "end")
self.text1.insert(1.0, sumxy)
messagebox.showinfo("Sum of {} and {}".format(x,y),
"Sum of {} and {} = {}".format(x, y, sumxy))
if __name__ == "__main__":
root = tk.Tk()
myapp = App(root)
root.mainloop()
I'll be referring to python in this question.
Ok, let's say i have a script that renames 1000 files.How do i multithread it?
I thought about dividing the files into chunks but it makes the code too complex, and to run 1000 thread, one for each file, isn't going to work.
Here is the code.
import os
import tkinter.messagebox
import tkinter.ttk
import tkinter.filedialog
from tkinter import Tk, StringVar, Text, END
print("""
A little reminder!
Any file that gets renamed can't be undo,so don't screw around with this.
NOTE : Careful with the extension,you might lose some files this way.
""")
class Rename:
def __init__(self,path): self.p = path
def rename(self):
try:
files = os.listdir(self.p)
i = 0
os.chdir(self.p)
while i <= len(files):
ext = files[i].split(".")[-1]
#You can change the renaming variable,for example you may add "file{}.{}".format(i,ext)..
#also,don't play with the ext if you don't know what you're doing..
os.rename(files[i],"{}.{}".format(i,ext))
i += 1
yield "Now renaming {}".format(files[i])
except OSError as e: print("Error -> {}".format(e))
except IndexError: pass
class GUI:
def __init__(self):
self.root = Tk()
self.root.wm_title("FileRenamer")
self.root.config(background = "black")
# Label
self.label = tkinter.ttk.Label(self.root, text = "Path: ")
self.label.config(foreground = "white", background = "black", font = ("Arial", 16))
self.label.grid(row = 0, column = 0)
# File dialog
self.path = StringVar()
self.filepath = tkinter.ttk.Button(self.root, text = "Choose", command = self.askPath).grid(row = 0, column = 1)
# TextWidget
self.text = Text(self.root, height = 5, width = 50)
self.text.config(foreground = "white", background = "black", font = ("Arial", 12))
self.text.grid(row = 3, column = 0, columnspan = 2)
# Button
self.button = tkinter.ttk.Button(self.root, text = "Rename", command = self.rename)
self.button.grid(row = 2, column = 1, columnspan = 2)
self.root.mainloop()
def askPath(self):
self.path = tkinter.filedialog.askdirectory()
def rename(self):
path = os.path.abspath(self.path)
rem = Rename(path)
for im in rem.rename():
self.text.insert(END, "{}\n".format(im))
# Make sure that you add another "\" to the path you enter, otherwise you'll get an error.
r = GUI()
I have a bit of code in a loop that outputs 2 buttons and a label, but after that it continues, but I want it to not do anything until the user hits a button. If any of you know how to do that it would help a ton. I have no commands in it since I am not sure how I will do this.
"more" is if the user wants another Flashcard, with 1 being yes and 0 being no.
x is the flash card you are on.
while more == "1":
if x <= 1:
self.flashCardText = Label(self.flashcards, text = flashcard[x][y]).grid(row = 1, column = 2)
self.flipButton = Button(self.flashcards, text = "Flip", command = lambda: flip()).grid(row = 2, column = 1)
self.nextButton = Button(self.flashcards, text = "Next", command = lambda: x += 1).grid(row = 2, column = 3)
At the moment you are creating lots of buttons in a while loop. So you can do it like that. What you can do, is to create some sort of dialog (example below). Can't say much without full code of yours, but the example below should be useful:
from tkinter import *
top = Tk()
class Test(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.x = 0
flashCardText = Label(self, text = print('flashcard')).grid(row = 1, column = 2)
flipButton = Button(self, text = "Flip", command = lambda: print('flip')).grid(row = 2, column = 1)
nextButton = Button(self, text = "Next", command = self._test_output).grid(row = 2, column = 3)
self.grid()
def _test_output(self):
if self.x < 2:
print("increasing x")
self.x +=1
else:
print("x is 2")
self.master.destroy()
t = Test(top)
top.mainloop()
So basically, in this example the Test window is being showed until self.x gets to 2. 'self.x' is being increased with each press of Next button. In this example other buttons don't do much.