Connect a message box to a button - python

I want to be able to click the button and have the message box display the code generated. Here's part of the code:
global s
letters = [random.choice('BCDFGHJKMPQRTVWXYYZ') for x in range(19)]
numbers = [random.choice('2346789') for x in range(6)]
s = letters + numbers
random.shuffle(s)
s = ''.join(s)
global Code
Code = Entry(state='readonly')
def callback():
Code = Entry(state='readonly', textvariable=s)
Code.grid(row=0, pady=20)
generate=PhotoImage(file='generate.gif')
G = Button(image=generate , command=callback, compound=CENTER)
G.grid(row=1, padx=206.5, pady=20)

Fixed a few things up with comments:
from Tkinter import *
import random
root = Tk()
letters = [random.choice('BCDFGHJKMPQRTVWXYYZ') for x in range(19)]
numbers = [random.choice('2346789') for x in range(6)]
s = letters + numbers
random.shuffle(s)
s = ''.join(s)
# Rather than use global variables, which is generally a bad idea, we can make a callback creator function, which takes the formerly global variables as arguments, and simply uses them to create the callback function.
def makeCallback(sVariable):
def callback():
# This will set the text of the entry
sVar.set(s)
return callback
# Use a StringVar to alter the text in the Entry
sVar = StringVar(root)
# You can use an Entry for this, but it seems like a Label is more what you're looking for.
Code = Entry(root, state='readonly', textvariable=sVar)
# Create a callback function
callback = makeCallback(sVar)
Code.grid(row=0, pady=20)
generate=PhotoImage(file='generate.gif')
G = Button(root, image=None , command=callback, compound=CENTER)
G.grid(row=1, padx=206.5, pady=20)

Related

How to change values from a matrix GUI tkinter?

I want to change a number from a matrix and then display it in the same tk window, but I find it hard to work with variables from an input. The r[][] should be the matrix formed with the user's input. And after all I have to display the matrix with the modification: r[0][1] += 5, in the same tk window.
from tkinter import *
import numpy as np
root = Tk()
def process():
values = [e1.get(),e2.get(),e3.get(),e4.get()]
a = np.zeros((2,2),dtype=np.int64)
for i in range(2):
for j in range(2):
a[i][j] = values[i*2+j]
print(a)
e1 = Entry(root)
e2 = Entry(root)
e3 = Entry(root)
e4 = Entry(root)
e1.grid(row=0,column=0,padx=10,pady=10)
e2.grid(row=0,column=1)
e3.grid(row=1,column=0,padx=10,pady=10)
e4.grid(row=1,column=1)
b = Button(root,text='Process',command=process)
b.grid(row=2,column=0,columnspan=4,sticky=E+W)
root.mainloop()
r=[[e1.get(),e2.get()],[e3.get(),e4.get()]]
r[0][1] += 5
Tkinter GUI programs are event-driven which requires using a different programming paradigm than the one you're probably familiar with which is called imperative programming. In other words, just about everything that happens is done in response to something the user has done, like typing on the keyboard, clicking on a graphical button, moving the mouse, etc.
I think the code below will give you a good idea of how to do what you want in a framework like that. It creates a StringVar for each Entry widget, which has the advantage what's displayed in each Entry will automatically be updated whenever the corresponding StringVar is changed (make that more-or-less automatic).
To determine which StringVar is associated with a given Entry, a separate dictionary is created which maps the internal tkinter variable name to corresponding Python variable. The internal tkinter variable name is obtained by using the universal cget() widget method.
import tkinter as tk
from tkinter.constants import *
ROWS, COLS = 2, 2
def process(entry_widgets, row, col):
var_name = entry_widgets[row][col].cget('textvariable')
var = root.variables[var_name]
try:
value = float(var.get())
except ValueError: # Something invalid (or nothing) was entered.
value = 0
var.set(value+5) # Update value.
root = tk.Tk()
# Create a grid of Entry widgets.
entries = []
root.variables = {} # To track StringVars.
for x in range(COLS):
row = []
for y in range(ROWS):
var = tk.StringVar(master=root) # Create variable.
root.variables[str(var)] = var # Track them by name.
entry = tk.Entry(root, textvariable=var)
entry.grid(row=x, column=y)
row.append(entry)
entries.append(row)
btn = tk.Button(root, text='Process', command=lambda: process(entries, 0, 1))
btn.grid(row=2, column=0, columnspan=COLS, sticky=E+W)
root.mainloop()
Would this be what you're looking for? I deleted a bunch of code that seems to do nothing in context -- you just want to replace the text in the corner box right?
from tkinter import *
def process():
replace(e4)
def replace(entry_loc):
temp = int(entry_loc.get())
temp += 5
entry_loc.delete(0,500)
entry_loc.insert(0, temp)
root = Tk()
var_e1 = StringVar
var_e2 = StringVar
var_e3 = StringVar
var_e4 = StringVar
e1 = Entry(root, textvariable=var_e1)
e2 = Entry(root, textvariable=var_e2)
e3 = Entry(root, textvariable=var_e3)
e4 = Entry(root, textvariable=var_e4)
e1.grid(row=0, column=0, padx=10, pady=10)
e2.grid(row=0, column=1)
e3.grid(row=1, column=0, padx=10, pady=10)
e4.grid(row=1, column=1)
b = Button(root, text='Process', command=process)
b.grid(row=2, column=0, columnspan=4, sticky=E + W)
root.mainloop()

Global Variable Undefined? Can't get label to display global variable from function

This is a little program I am making to learn Python which is a NPC Trait Generator that generates random words from a text file.
My random generator works, but I can't get it to display properly in the label. I currently have pertrait set to global but it doesn't seem to pick up the variable to display in the label? I tried setting up StringVar but I couldn't seem to get that to work properly either.
import tkinter as tk
from tkinter import font
# Random Personality generation from text list
def gen():
global pertrait
pertrait = print(random.choice(open(
'F:\\Desktop\\python\\RandomGenerator py\\CharTraitList.txt').read(
).split()).strip())
root = tk.Tk()
root.title("NPC Trait Generator")
root.geometry("500x200")
frame = tk.Frame(root)
frame.pack()
# define font
fontStyle = font.Font(family='Courier', size=44, weight='bold')
# background image variable and import
paper = tk.PhotoImage(
file='F:\\Desktop\\python\\RandomGenerator py\\papbckgrd.png')
butQuit = tk.Button(frame,
text="Quit",
fg="red",
command=quit)
butQuit.pack(side=tk.LEFT)
ButGen = tk.Button(frame,
text="Generate",
command=gen)
ButGen.pack(side=tk.RIGHT)
# Label generation
Trait1 = tk.Label(root,
compound=tk.CENTER,
text=pertrait,
font=fontStyle)
# image=paper) .pack(side="right")
Trait1.pack()
root.mainloop()
print() doesn’t return a value, and you neglected to call gen()!
Change:
pertrait = print(random.choice(open(
'F:\\Desktop\\python\\RandomGenerator py\\CharTraitList.txt').read(
).split()).strip())
To:
pertrait = random.choice(open(
'F:\\Desktop\\python\\RandomGenerator py\\CharTraitList.txt').read(
).split()).strip()
But really it would be much better t avoid the global - make gen() return the value and assign the result of gen() ot pertrait

Passing an object in lambda in tkinter button callback

I am trying to use lambda to create callbacks for tkinter buttons.
There are multiple buttons and each callback needs to pass an object inside it. Following code is what I am doing and is running fine
var0 = tk.StringVar()
label = tk.Label(top, bg = "White",height = 2, width = 12,textvariable=var0, justify="right")
def b0Callback(var):
var.set(var.get()+"0")
return
# creating a label which will print value of the any of the 0-9 button pressed
# creating a button 0
b0 = tk.Button(numFrame0, height = 1, width = 4, bg = "grey", text =
"0",command = lambda: b0Callback(var0))
#there are more buttons like that
var0 is used to update a label. Above code is working fine but I have to create callback for 0 to 9 and I have to just repeat above definition. So I tried using following example from this tutorial
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
Using it I did following
def Callback(n):
return lambda var.set(var.get()+n)
b0Callback = Callback("0")
This shows error invalid index in the return line at var.set
Is there any way to pass var0 in this case to avoid this error?
Maybe its only me, but I don't see a reason for using lambda if you just want to add a number to the label text.
Lets make a function for it that gets your StringVar() as a variable and adds some number to it:
def button_callback(str_var, number):
str_var.set(str_var.get() + str(number))
To run this command we simply put it in the code as a lambda function, otherwise it will run upon initialization (because we are providing a function instead of a reference).
So to run it within a button we declare it like this:
my_button = Button(root, text='Some text here', command=lambda: button_callback(my_string_var, 5))
The '5' could be potentially changed to any other number.
I have now solved the problem, here is the final code:
I have also changed the number of buttons to 300 and added code to arrange them all in a nice grid, just for fun. (You can change this to however many you want by changing for number in range(1, whatever).
import tkinter as tk
class Window(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.var0 = tk.StringVar()
self.var0.set('0')
# creating buttons and adding them to dictionary
self.buttons = {}
for number in range(1, 301):
self.buttons.update({'button' + str(number): tk.Button(self, height=1, width=4, bg="grey", text=number)})
label = tk.Label(self, textvariable=self.var0, font='none 50')
label.grid(column=0, row=0)
for button in self.buttons:
self.buttons[button].bind('<Button-1>', lambda event, num=button[6:]: self.Callback(event, num))
self.buttons[button].grid(column=(int(button[6:]) % 10), row=(int(button[6:]) / 10) + 1)
def Callback(self, event, num):
self.var0.set(num)
self.update()

How to get values of checkbuttons from for loop tkinter python

I am new to programming in tkinter and am very stuck on using checkbuttons. I have created multiple checkbuttons in one go, all with different text for each one and a different grid position. However I have no idea how to get the value of each button or how to even set it. I want to be able to get the state/value for each button and if it is checked, then another function is called. How do I set and call the value/state of each button? Can this be done in a for loop or do I have to create them individually?
def CheckIfValid(self, window):
Class = self.ClassChosen.get()
Unit = self.UnitChosen.get()
Topic = self.TopicChosen.get()
if Class == '' or Unit == '' or Topic == '':
tm.showinfo("Error", "Please fill in all boxes")
else:
QuestionData = OpenFile()
QuestionsList = []
for x in range (len(QuestionData)):
#if QuestionData[x][2] == Topic:
QuestionsList.append(QuestionData[x][0])
for y in range(len(QuestionsList)):
self.ButtonVal[y] = IntVar()
Checkbutton(window, text = QuestionsList[y], padx = 20, variable = self.ButtonVal[y]).grid(row = 12 + y, column = 2)
ConfirmSelection = Button(window, text = "Set Homework", command = lambda: SetHomeworkClass.ConfirmHomework(self)).grid()
print(variable.get()) #here I would like to be able to get the value of all checkbuttons but don't know how
You use the list of IntVars either called from a command= in the Checkbutton or in the Button. Don't know why you are calling another class's object, SetHomeworkClass.objectConfirmHomework(self). It doesn't look like that will work as you have it programmed, as that is another name space and the list of IntVars is in this name space, but that is another topic for another thread.
try:
import Tkinter as tk # Python2
except ImportError:
import tkinter as tk # Python3
def cb_checked():
# remove text from label
label['text'] = ''
for ctr, int_var in enumerate(cb_intvar):
if int_var.get(): ## IntVar not zero==checked
label['text'] += '%s is checked' % cb_list[ctr] + '\n'
root = tk.Tk()
cb_list = [
'apple',
'orange',
'banana',
'pear',
'apricot'
]
# list of IntVar for each button
cb_intvar = []
for this_row, text in enumerate(cb_list):
cb_intvar.append(tk.IntVar())
tk.Checkbutton(root, text=text, variable=cb_intvar[-1],
command=cb_checked).grid(row=this_row,
column=0, sticky='w')
label = tk.Label(root, width=20)
label.grid(row=20, column=0, sticky='w')
# you can preset check buttons (1=checked, 0=unchecked)
cb_intvar[3].set(1)
# show what is initially checked
cb_checked()
root.mainloop()

Change label text on button using values from tuple click tkinter

I have a list of strings sorted in a tuple like this:
values = ('1.Python','2.Ruby','3.PHP','4.Perl','5.JavaScript')
My simple code is:
from tkinter import *
root = Tk()
values = ('1.Python','2.Ruby','3.PHP','4.Perl','5.JavaScript')
ru = Button(root,
text="Next",
)
ru.grid(column=0,row=0)
lab = Label(root,
text=values[0])
lab.grid(column=1,row=0)
ru2 = Button(root,
text="Previous"
)
ru2.grid(column=2,row=0)
root.mainloop()
I have two tkinter buttons "next" and "previous", the text value of the Label is directly taken from the tuple (text=value[0]), however I would want to know how to show the next string from the tuple when the next button is pressed, and how to change it to the previous values when the "previous" button is pressed. I know it can be done using for-loop but I cannot figure out how to implement that. I am new to python.
Use Button(..., command=callback) to assign function which will change text in label lab["text"] = "new text"
callback means function name without ()
You will have to use global inside function to inform function to assign current += 1 to external variable, not search local one.
import tkinter as tk
# --- functions ---
def set_next():
global current
if current < len(values)-1:
current += 1
lab["text"] = values[current]
def set_prev():
global current
if current > 0:
current -= 1
lab["text"] = values[current]
# --- main ---
values = ('1.Python','2.Ruby','3.PHP','4.Perl','5.JavaScript')
current = 0
root = tk.Tk()
ru = tk.Button(root, text="Next", command=set_next)
ru.grid(column=0, row=0)
lab = tk.Label(root, text=values[current])
lab.grid(column=1, row=0)
ru2 = tk.Button(root, text="Previous", command=set_prev)
ru2.grid(column=2, row=0)
root.mainloop()
BTW: if Next has to show first element after last one
def set_next():
global current
current = (current + 1) % len(values)
lab["text"] = values[current]
def set_prev():
global current
current = (current - 1) % len(values)
lab["text"] = values[current]

Categories