Issue with displaying quantity button in proper position in Python - python-3.x

I am building a page using Python, it has 2 frames, one frame is to display the products and when we click upon the product it should perform a mouseclickevent and should display in second frame. Along with the product name it should display quantity with + and - option to increment and decrement.
I am using pycharm professional 2017.3.2
This is my code:
def OnDoubleClick(event):
a = tree.selection()[0]
price = tree.item(a, "values")
amt = price[1]
print("amt is :",amt)
t1=0
v1 = IntVar(receiptbox, value='1')
def onMinus():
if (v1.get()>0):
v1.set(v1.get() - 1)
btn1 = Button(receiptbox, justify=CENTER, text="-
",command=onMinus,bg="#33ccff")
receiptbox.insert(END, "\n")
btn1.pack(side=LEFT,anchor=E)
e1 = Entry(receiptbox, justify=CENTER, textvariable=v1, width=4, state="readonly")
e1.pack(side=LEFT,anchor=E)
def onPlus():
v1.set(v1.get() + 1)
# receiptbox.delete("1.0", END)
if(v1.get()>1):
receiptbox.delete("1.0", END)
# v1.set(v1.get() + 1)
var = v1.get()
price = tree.item(a, "values")
amt1 = (price[1])
# amt2 = int(amt1)
# t1 = float(amt1) * (var)
receiptbox.insert(END, tree.item(a, "text") + " Sub Total: "+str(float(amt1) * (var)))
receiptbox.insert(END,"\n")
btn2 = Button(receiptbox, justify=CENTER, text="+", command=onPlus,bg="#33ccff")
btn2.pack(side=LEFT,anchor=E)
receiptbox.insert(END,"\n")
if (v1.get()==1):
total = (v1.get() * amt)
print("Total is :"+str(total))
receiptbox.insert(END, tree.item(a, "text") + " Sub Total: " + str(total))
receiptbox.insert(END, "\n")
receiptbox.insert(END, "\n\n")
I am able to display the list of product and mouseclick is working fine. Products are listed from the database. The issue is with the quantity button. Its not coming in the proper position. I mean it should display in the same row along with the product name.

Related

I'm trying to make a wage calculator but when i try to print the wages it shows zeros

I'm trying to make a wage calculator.
I'm trying to make a wage calculator but when I try to print the wages it shows zeros. I'm using Tkinter
app = Tk()
hoursWorkedWeek_text = IntVar()
hoursWorkedWeek_label = Label(app, text="Hours worked per week: ", font=("bold", 13), pady = 20)
hoursWorkedWeek_label.grid(row=0,column=0, sticky=W)
hoursWorkedWeek_entry = Entry(app, textvariable=hoursWorkedWeek_text)
hoursWorkedWeek_entry.grid(row=0,column=1)
there are 3 more like this where it gets the rate etc
_hpw = hoursWorkedWeek_entry.get()
hpw = float(_hpw)
_rph = rateEarnedPH_entry.get()
rph = float(_rph)
_oh = overtimeHours_entry.get()
oh = float(_oh)
_rot = rateForOvertime_entry.get()
rot = float(_rot)
def calculate():
_salaryPerWeek = hpw * rph + oh * rot
salaryPerWeek = str(_salaryPerWeek)
_salaryPerMonth = salaryPerWeek * 4
salaryPerMonth = str(_salaryPerMonth)
_salaryPerYear = salaryPerMonth * 12
salaryPerYear = str(_salaryPerYear)
salaryPerWeek_text = "Your Weekly Salary is " + salaryPerWeek
salaryPerMonth_text = "Your Monthly Salary is " + salaryPerMonth
salaryPerYear_text = "Your Yearly Salary is " + salaryPerYear
print(salaryPerWeek_text)
T = Text(app, height=5, width=52)
T.insert(tkinter.END, salaryPerWeek_text)
T.insert(tkinter.END, salaryPerMonth_text)
T.insert(tkinter.END, salaryPerYear_text)
and then there is the Calculate button
#Buttons
calculate_btn = Button(app, text="Calculate", width=12, command=calculate)
calculate_btn.grid(row=2,column=1, pady=20)
app.title("Salary Calculator")
app.geometry("700x400")
#Start program
app.mainloop()
Can you please explain to me what was wrong? I'm new to programming
and a rating would be nice
Thank You

Problem with dynamically changing which command a button calls in tkinter

In this simple calculator GUI, I'm creating a frame template using classes. The frame has 2 labels, 2 entry boxes, and a button. I'd like the button to run a specific command depending on the function_call variable passed when initializing - but this doesn't work. The two_points function should be called for the first object, and one_point should be called for the second. How do I dynamically change which command is called based on which object I'm using? Thank you for taking the time to read this.
from tkinter import *
root = Tk()
root.title("Simple Slope Calculator")
class Slope_Calc:
# Variable info that changes within the frame
def __init__(self, master, num_1, num_2, frame_name, label_1_name, label_2_name, function_call):
self.num_1 = int(num_1)
self.num_2 = int(num_2)
self.frame_name = frame_name
self.label_1_name = label_1_name
self.label_2_name = label_2_name
self.function_call = function_call
# Frame template
self.frame_1 = LabelFrame(master, text = self.frame_name, padx = 5, pady = 5)
self.frame_1.grid(row = self.num_1, column = self.num_2, padx = 10, pady = 10)
self.label_1 = Label(self.frame_1, text = self.label_1_name)
self.label_1.grid(row = 0, column = 0)
self.entry_1 = Entry(self.frame_1)
self.entry_1.grid(row = 0, column = 1)
self.label_2 = Label(self.frame_1, text = self.label_2_name)
self.label_2.grid(row = 1, column = 0)
self.entry_2 = Entry(self.frame_1)
self.entry_2.grid(row = 1, column = 1)
self.calc_button = Button(self.frame_1, text = "Calculate", command = self.function_call) # This is what doesn't work
self.calc_button.grid(row = 1, column = 2, padx = 5)
# Strips string of spaces and parentheses
# Returns a list of relevant ordered pair
def strip_string(self, entry_num):
ordered_pair = entry_num.get().split(", ")
ordered_pair[0] = ordered_pair[0].replace("(", "")
ordered_pair[1] = ordered_pair[1].replace(")", "")
return(ordered_pair)
# Calculates slope based on one point and y-intercept
def one_point(self):
pair_1 = self.strip_string(self.entry_1)
b = int(self.entry_2.get())
m = (int(pair_1[1]) - b)/(float(pair_1[1]))
label_3 = Label(self.frame_1, text = "SLOPE-INTERCEPT EQUATION: y = " + str(m) + "x + " + str(b))
label_3.grid(row = 2, column = 0, columnspan = 2)
# Calculates slope based on two points given
def two_points(self):
pair_1 = self.strip_string(self.entry_1)
pair_2 = self.strip_string(self.entry_2)
m = (int(pair_2[1]) - int(pair_1[1]))/float(int(pair_2[0]) - int(pair_1[0]))
b = (int(pair_1[1])) - (m*int(pair_1[0]))
label_3 = Label(self.frame_1, text = "SLOPE-INTERCEPT EQUATION: y = " + str(m) + "x + " + str(b))
label_3.grid(row = 2, column = 0, columnspan = 2)
# Calling each object
two_p = Slope_Calc(root, 0, 0, "Two Points", "First Ordered Pair", "Second Ordered Pair", "two_points")
one_p = Slope_Calc(root, 0, 1, "One Point and Y-Intercept", "Ordered Pair", "Y-intercept", "one_point")
root.mainloop()
The command keyword argument of the Button constructor is supposed to be a function.
Here you give it instead a string which is the name of the method of self that should be called. So you must first get this method using setattr to be able to call it. This should do it:
def call():
method = getattr(self, self.function_call)
method()
self.calc_button = Button(
self.frame_1,
text = "Calculate",
command = call)
You then have an error in strip_string but that's another story.

Winodow not appearing in Tkinter

this code is in referrence to a cricket scoring program
When a button is pressed in my program, it runs a validation based of the users input and if it goes through, it should open a new window. But every time I run the code, the window.
def team_names(team):
global team_amount
global team_name_input
global team_amount_test
team_name_input = Toplevel(master)
confirm_screen.withdraw()
enter_names = Label(team_name_input, text = "Enter amount of players in " + team).grid(row = 0, column = 1)
enter_names2 = Label(team_name_input, text="(Between 2 and 11)").grid(row=1, column=1)
team_amount_test = Entry(team_name_input, width = 20)
team_amount_test.grid(row = 2, column = 1)
submit_amount = Button(team_name_input, text="Submit", command= lambda:amount_validation(team_1_array)).grid(row=3, column=1) <--- Button to open new winodw
def amount_validation(team_array):
team_num = 1
team_amount = int(team_amount_test.get())
if team_num == 1:
current_team = team_1
elif team_num == 2:
current_team = team_2
#Validation
if team_amount < 2 or team_amount > 11:
error = Label(team_name_input, text = "Invalid amount, try again").grid(row = 4, column = 1)
elif team_amount > 2 or team_amount < 11:
player_num = 1
name_input_win = Toplevel(master) #Should open new winodw here
#name_input_win.geometry("200x150")
team_name_input.withdraw()
first = Label(name_input_win, text = "Enter player " + str(player_num) + " for " + str(current_team)).grid(row = 0, column = 1)
name_input = Entry(name_input_win)
name_input.grid(row = 1, column = 1)
name = str(name_input.get())
for i in range(0, player_num):
p = None
while not p or p in team_array:
#first = Label(name_input, text="Enter player " + str(player_num) + " for " + str(current_team)).grid(row=0,column=1)
if p in team_array:
error = Label(name_input, text = "Player already entered").grid(row = 2, column = 1)
team_array.append(p)
player_num = player_num + 1
Any help will be appriciated ^-^

How to use a variable to determine which index in a list to use

I've been testing a program of mine lately, and each time I've tested it, I've had the same error message:
IndexError: list index out of range
The code is
def NewOffer(CurrentOffer, MaximumPrice, y, NoOfBuyers, Buyers):
x = random.randint(0, NoOfBuyers)
SelectedBuyer = Buyers[x]
if CurrentOffer < MaximumPrice[x]:
CurrentOffer = CurrentOffer + random.randint(1, 500)
print(str(SelectedBuyer) + " renewed their offer and are now willing to pay £" +
str(CurrentOffer) + " for " + str(AuctionedItem))
x = random.randint(0, NoOfBuyers)
NewOffer(CurrentOffer, MaximumPrice, y, NoOfBuyers, Buyers)
time.sleep(3)
And the only line that trips up every single time is the ''' SelectedBuyer = Buyers[x] '''. How do i solve this?
It's seems that the Buyers list don't have an element in position x you can check it by
Buyers[x] if len(Buyers) >= x else #some value if it's not in the len()
or
x = random.randint(0, len(Buyers) - 1)
To generate a random number that in the length of the Buyers list.
You may need to do the same for MaximumPrice
I tried to understand your code and came up with another implementation:
import random
import time
buyers = (
("Peggy Carter", 10000),
("Phil Coulson", 7500),
("Edwin Jarvis", 5000),
("Justin Hammer", 2300),
("Darcy Lewis", 1750),
("Christine Everhart", 6490),
)
auctioned_item = "The Tesseract"
current_offer = random.randint(1, 5000)
print(f"The starting price for {auctioned_item} is £{current_offer}")
current_buyer = None
def auction_rounds(current_offer, buyers):
current_buyer = None
outbid = False
while not outbid:
(next_buyer, next_maximum) = random.choice(buyers)
while next_buyer == current_buyer:
(next_buyer, next_maximum) = random.choice(buyers)
outbid = current_offer > next_maximum
if not outbid:
current_buyer = next_buyer
yield (current_buyer, current_offer)
next_offer = random.randint(current_offer, min(current_offer + 500,
next_maximum))
current_buyer, current_offer = next_buyer, next_offer
else:
print(f'This is too much for {next_buyer}')
for (current_buyer, current_offer) in auction_rounds(current_offer, buyers):
print(f"{current_buyer} is offering to pay £{current_offer}",
"for", auctioned_item)
#time.sleep(3)
if current_buyer is None:
print("The first buyer wasn't even able to pay the starting price")
else:
print(f"Sold! The auction item ({auctioned_item}) is awarded to {current_buyer} for £{current_offer}")
I hope this is something like that, that you were looking for.

How to make dynamic list changes in python?

Guy am trying to create pages for my tk GUI,so I got this code below that works perfectly,on click of next button it get the first 5 and till end of 100 and vice versa on click of prev button
import tkinter as tk
import math
items = [str(n) for n in range(100)]
page = 0
per_page = 5
n_pages = math.ceil(len(items) / per_page)
def update_list():
print(page)
start_index = int(page * per_page)
end_index = int((page + 1) * per_page)
items_in_page = items[start_index:end_index]
view_text = "Page %d/%d: %s" % (page + 1, n_pages, ", ".join(items_in_page))
def change_page(delta):
global page
page = min(n_pages - 1, max(0, page + delta))
update_list()
def prev_btn():
change_page(-1)
def next_btn():
change_page(+1)
win = tk.Tk()
win.title("clickers")
tk.Button(win, text="next", command=next_btn).pack()
tk.Button(win, text="prev", command=prev_btn).pack()
show = tk.Entry(win)
show.pack()
update_list() # to initialize `show`
win.mainloop()
I want to adjust this part of code
items = [str(n) for n in range(100)]
into a list like this,and get it working as just switching them doesn't work
list_ = [1,2,3], [4,5,6], [7,8,9], [10,11,12], [13,14,15], [16,17,18]]
items =[str(n) for n in list_]
so oncick of next button it return first 2(any number choice) list and vice versa for prev,when that's done,please note that this list originally comes from multiple rows of a database that's has been selected,not just some variable holding a list like I have it,so I need help on how to directly use the loop to get first 2 rows(2 list) from the database,and immediate past 2 rows for prev button

Resources