Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 将GUI合并到我的裁剪和堆栈程序中_Python 3.x_User Interface_Tkinter_Directory - Fatal编程技术网

Python 3.x 将GUI合并到我的裁剪和堆栈程序中

Python 3.x 将GUI合并到我的裁剪和堆栈程序中,python-3.x,user-interface,tkinter,directory,Python 3.x,User Interface,Tkinter,Directory,我是python(3.8)的新手,我刚刚编写了一个程序,它将在一个目录中获取图像并裁剪它们,然后将它们全部堆叠起来。我目前正在尝试添加一个GUI,使它看起来更漂亮。我已经阅读了一些关于如何使用tkinter的指南,它们都单独讨论了每个小部件。我对使用GUI中的条目信息输入程序运行的符号有点困惑。我已经为程序编写了一个通用GUI。在我的程序中,输入文件的文件目录和保存位置都是常量,用户可以输入(x1,y1),(x2,y2)和图像数量。如果我想让GUI提示输入和保存文件目录,我一直在尝试这样做: d

我是python(3.8)的新手,我刚刚编写了一个程序,它将在一个目录中获取图像并裁剪它们,然后将它们全部堆叠起来。我目前正在尝试添加一个GUI,使它看起来更漂亮。我已经阅读了一些关于如何使用tkinter的指南,它们都单独讨论了每个小部件。我对使用GUI中的条目信息输入程序运行的符号有点困惑。我已经为程序编写了一个通用GUI。在我的程序中,输入文件的文件目录和保存位置都是常量,用户可以输入(x1,y1),(x2,y2)和图像数量。如果我想让GUI提示输入和保存文件目录,我一直在尝试这样做:

def inputfile():
    master.filename = filedialog.askdirectory()
    print(master.filename)
...
input = Button(master, text="Input Files", command="inputfile")
input.grid(column=5, row=6, columnspan=2, pady=6)
然后在我的代码中,用filename.get()替换目录

我还尝试用x1input.get()替换代码中的所有x1、y1、x2、y2值。这是正确的做法吗

附件是程序和GUI代码。谢谢你抽出时间

节目

from PIL import Image
from natsort import natsorted
import glob
import gc

# Convert coordinate list into variables
print("Type in the coordinates for the upper left (x1,y1) and bottom right (x2,y2) points")
coordinates = list(map(int, input("Separate values with a space (x1 y1 x2 y2): ").strip().split()))[:4]
x1, y1, x2, y2 = coordinates
image_count = int(input("How many images are being stacked? "))
print("Generating image...")

# Generate final image first
# Width dependent on whether image is horizontal or vertical
if (y2 - y1) > (x2 - x1):
    width = (y2 - y1)
    height = (x2 - x1)
else:
    width = (x2 - x1)
    height = (y2 - y1)

# Width is constant, total_height accounts for height above and the total number of images
total_height = (image_count * height)
new_im = Image.new('RGB', (width, total_height))  # Create a new colored image (RGB)

# Keep outside of loop, if not, will reset y_offset each time
# Indicates position of where to paste cropped image
# Counter used to show progress of program
y_offset = 0
counter = 0

# Accessing all the files using the glob module
# The function natsorted sorts values the way Windows does
# ..\\ allows the program to obtained images from the data file relative to the script's location
# Opens all the files with the variable img in folder and adds them one by one to a list named image_list
for filename in natsorted(
        glob.glob("..\\One_Dimensional_Reaction_Diffusion_Program\\image_crop_input\\" + "*.*", recursive=True)):
    img = Image.open(filename)

    # Cropping function
    selected_region = (x1, y1, x2, y2)  # selected region from previous user input
    cropped_region = img.crop(selected_region)  # taking opened image and cropping to selected region
    if (y2 - y1) > (x2 - x1):  # If cropped area is vertical, rotate into horizontal position
        rotated_image = cropped_region.rotate(90, expand=1)  # Expand 1 ensures image isn't cut off while rotating
    else:
        rotated_image = cropped_region  # Does nothing if image is horizontal
    img.close()  # Closes the initially opened image
    gc.collect()

    new_im.paste(rotated_image, (0, y_offset))  # (x,y) indicates which direction to offset in
    y_offset += rotated_image.size[1]  # y_offset (which had position 0) + the height of the image
    counter += 1
    print(counter, " out of ", image_count, "completed.")  # Shows progress of program
    if counter == image_count:  # Will stop program when counter reaches number of images
        break
final_im = new_im.rotate(180, expand=1)  # stacking goes from top to bottom, rotate images at the end
final_im.save("..\\One_Dimensional_Reaction_Diffusion_Program\\image_crop_output\\stacked_image.tiff", quality=95)
print("Image completed and can be found in the output folder.")
input("Press ENTER to close program.")  # prevents prompt from instantly closing
图形用户界面代码

from tkinter import *
from tkinter import filedialog
from PIL import Image
from natsort import natsorted
import glob
import gc

master = Tk()
master.title("One Dimensional Reaction Diffusion Program")
master.geometry("440x270")

def inputfile():
    master.filename = filedialog.askdirectory()
    print(master.filename)


header1 = Label(master, text="One Dimensional Reaction Diffusion Program\n"
                             "Created by: Alexander Tang\n")

header1.grid(sticky="N", columnspan=8)
instructions = Label(master, text="Type in the coordinates for the upper left (x1,y1) and bottom right (x2,y2) points:")
instructions.grid(sticky="W", columnspan=8)

x1 = Label(master, text="x1: ")
x1.grid(sticky="E", column=0, row=2)
x1input = Entry(master, width=5)
x1input.grid(sticky="W", column=1, row=2)

y1 = Label(master, text="y1: ")
y1.grid(sticky="E", column=2, row=2)
y1input = Entry(master, width=5)
y1input.grid(sticky="W", column=3, row=2)

x2 = Label(master, text="x2: ")
x2.grid(sticky="E", column=4, row=2)
x2input = Entry(master, width=5)
x2input.grid(sticky="W", column=5, row=2)

y2 = Label(master, text="y2: ")
y2.grid(sticky="E", column=6, row=2)
y2input = Entry(master, width=5)
y2input.grid(sticky="W", column=7, row=2, pady=12)

count = Label(master, text="How many images are being stacked? ")
count.grid(sticky="W", column=0, row=4, columnspan=4)
countinput = Entry(master, width=5)
countinput.grid(stick="W", column=5, row=4, pady=3)

step1 = Label(master, text="1. Select the file location: ")
step1.grid(sticky="W", column=0, row=6, columnspan=4)
step2 = Label(master, text="2. Select the save location: ")
step2.grid(sticky="W", column=0, row=7, columnspan=4)

input = Button(master, text="Input Files", command="inputfile")
input.grid(column=5, row=6, columnspan=2, pady=6)
output = Button(master, text="Output Location")
output.grid(column=5, row=7, columnspan=2)
run = Button(master, text="Run", font="Helvetica, 18", bg="blue", fg="white")
run.grid(sticky="S", column=5, row=8, columnspan=2, pady=6)



mainloop()

第一个用于处理图像的代码必须放在函数中(但不带
input()
),以便可以使用参数运行它

 def process(directory, coordinates, image_count, outputdirectory=None):
然后您可以使用
input()
或GUI或网页获取参数并运行此函数

在我使用的同一个文件中

if __name__ == "__main__":
    main()
要运行此脚本并使用
input()
获取参数并运行
process()

也可以将其导入到其他脚本中并运行
process()
,而无需启动
main()

imageprocess.py

from PIL import Image
from natsort import natsorted
import glob
import gc
import os   # os.path.join(directory, filename)

def process(directory, coordinates, image_count, outputdirectory=None):

    x1, y1, x2, y2 = coordinates

    # Generate final image first
    # Width dependent on whether image is horizontal or vertical
    if (y2 - y1) > (x2 - x1):
        width = (y2 - y1)
        height = (x2 - x1)
    else:
        width = (x2 - x1)
        height = (y2 - y1)

    # Width is constant, total_height accounts for height above and the total number of images
    total_height = (image_count * height)
    new_im = Image.new('RGB', (width, total_height))  # Create a new colored image (RGB)

    # Keep outside of loop, if not, will reset y_offset each time
    # Indicates position of where to paste cropped image
    # Counter used to show progress of program
    y_offset = 0
    counter = 0

    # Accessing all the files using the glob module
    # The function natsorted sorts values the way Windows does
    # ..\\ allows the program to obtained images from the data file relative to the script's location
    # Opens all the files with the variable img in folder and adds them one by one to a list named image_list
    for filename in natsorted(glob.glob( os.path.join(directory, "*.*"), recursive=True)):
        img = Image.open(filename)

        # Cropping function
        selected_region = (x1, y1, x2, y2)  # selected region from previous user input
        cropped_region = img.crop(selected_region)  # taking opened image and cropping to selected region
        if (y2 - y1) > (x2 - x1):  # If cropped area is vertical, rotate into horizontal position
            rotated_image = cropped_region.rotate(90, expand=1)  # Expand 1 ensures image isn't cut off while rotating
        else:
            rotated_image = cropped_region  # Does nothing if image is horizontal
        img.close()  # Closes the initially opened image
        gc.collect()

        new_im.paste(rotated_image, (0, y_offset))  # (x,y) indicates which direction to offset in
        y_offset += rotated_image.size[1]  # y_offset (which had position 0) + the height of the image
        counter += 1
        print(counter, " out of ", image_count, "completed.")  # Shows progress of program
        if counter == image_count:  # Will stop program when counter reaches number of images
            break
    final_im = new_im.rotate(180, expand=1)  # stacking goes from top to bottom, rotate images at the end

    if outputdirectory is None:
        outputdirectory = directory
    final_im.save( os.path.join(outputdirectory, "stacked_image.tiff"), quality=95)

def main():
    # Convert coordinate list into variables
    print("Type in the coordinates for the upper left (x1,y1) and bottom right (x2,y2) points")
    coordinates = list(map(int, input("Separate values with a space (x1 y1 x2 y2): ").strip().split()))[:4]
    image_count = int(input("How many images are being stacked? "))
    print("Generating image...")

    process(directory, coordinates, image_count)

    print("Image completed and can be found in the output folder.")
    input("Press ENTER to close program.")  # prevents prompt from instantly closing

if __name__ == "__main__":
    main()
from tkinter import *
from tkinter import filedialog
from tkinter import messagebox
from PIL import Image
from natsort import natsorted
import glob
import gc

import imageprocess

# --- functions ---

def inputfile():
    master.inputdirectory = filedialog.askdirectory()
    print(master.inputdirectory)

def outputfile():
    master.outputdirectory = filedialog.askdirectory()
    print(master.outputdirectory)

def run():
    try:
        coordinates = [int(x1input.get()), int(x2input.get()), int(y1input.get()), int(y2input.get())]
        image_count = int(countinput.get())

        imageprocess.process(master.inputdirectory, coordinates, image_count, master.outputdirectory)

    except Exception as ex:
        print('ex:', ex)
        messagebox.showwarning("Warning", "Wrong arguments:\n" + str(ex))

# --- main ---

master = Tk()

master.inputdirectory = None   # default value at start
master.outputdirectory = None  # default value at start

master.title("One Dimensional Reaction Diffusion Program")
master.geometry("440x270")

header1 = Label(master, text="One Dimensional Reaction Diffusion Program\n"
                             "Created by: Alexander Tang\n")

header1.grid(sticky="N", columnspan=8)
instructions = Label(master, text="Type in the coordinates for the upper left (x1,y1) and bottom right (x2,y2) points:")
instructions.grid(sticky="W", columnspan=8)

x1 = Label(master, text="x1: ")
x1.grid(sticky="E", column=0, row=2)
x1input = Entry(master, width=5)
x1input.grid(sticky="W", column=1, row=2)

y1 = Label(master, text="y1: ")
y1.grid(sticky="E", column=2, row=2)
y1input = Entry(master, width=5)
y1input.grid(sticky="W", column=3, row=2)

x2 = Label(master, text="x2: ")
x2.grid(sticky="E", column=4, row=2)
x2input = Entry(master, width=5)
x2input.grid(sticky="W", column=5, row=2)

y2 = Label(master, text="y2: ")
y2.grid(sticky="E", column=6, row=2)
y2input = Entry(master, width=5)
y2input.grid(sticky="W", column=7, row=2, pady=12)

count = Label(master, text="How many images are being stacked? ")
count.grid(sticky="W", column=0, row=4, columnspan=4)
countinput = Entry(master, width=5)
countinput.grid(stick="W", column=5, row=4, pady=3)

step1 = Label(master, text="1. Select the file location: ")
step1.grid(sticky="W", column=0, row=6, columnspan=4)
step2 = Label(master, text="2. Select the save location: ")
step2.grid(sticky="W", column=0, row=7, columnspan=4)

btn_input = Button(master, text="Input Files", command=inputfile)
btn_input.grid(column=5, row=6, columnspan=2, pady=6)

btn_output = Button(master, text="Output Location", command=outputfile)
btn_output.grid(column=5, row=7, columnspan=2)

btn_run = Button(master, text="Run", font="Helvetica, 18", bg="blue", fg="white", command=run)
btn_run.grid(sticky="S", column=5, row=8, columnspan=2, pady=6)

mainloop()
现在您可以将其导入GUI,并使用按钮运行从GUI获取参数的函数,然后运行
process()

顺便说一句:它必须是函数名
command=function\u name
,而不是字符串
“function\u name”

gui.py

from PIL import Image
from natsort import natsorted
import glob
import gc
import os   # os.path.join(directory, filename)

def process(directory, coordinates, image_count, outputdirectory=None):

    x1, y1, x2, y2 = coordinates

    # Generate final image first
    # Width dependent on whether image is horizontal or vertical
    if (y2 - y1) > (x2 - x1):
        width = (y2 - y1)
        height = (x2 - x1)
    else:
        width = (x2 - x1)
        height = (y2 - y1)

    # Width is constant, total_height accounts for height above and the total number of images
    total_height = (image_count * height)
    new_im = Image.new('RGB', (width, total_height))  # Create a new colored image (RGB)

    # Keep outside of loop, if not, will reset y_offset each time
    # Indicates position of where to paste cropped image
    # Counter used to show progress of program
    y_offset = 0
    counter = 0

    # Accessing all the files using the glob module
    # The function natsorted sorts values the way Windows does
    # ..\\ allows the program to obtained images from the data file relative to the script's location
    # Opens all the files with the variable img in folder and adds them one by one to a list named image_list
    for filename in natsorted(glob.glob( os.path.join(directory, "*.*"), recursive=True)):
        img = Image.open(filename)

        # Cropping function
        selected_region = (x1, y1, x2, y2)  # selected region from previous user input
        cropped_region = img.crop(selected_region)  # taking opened image and cropping to selected region
        if (y2 - y1) > (x2 - x1):  # If cropped area is vertical, rotate into horizontal position
            rotated_image = cropped_region.rotate(90, expand=1)  # Expand 1 ensures image isn't cut off while rotating
        else:
            rotated_image = cropped_region  # Does nothing if image is horizontal
        img.close()  # Closes the initially opened image
        gc.collect()

        new_im.paste(rotated_image, (0, y_offset))  # (x,y) indicates which direction to offset in
        y_offset += rotated_image.size[1]  # y_offset (which had position 0) + the height of the image
        counter += 1
        print(counter, " out of ", image_count, "completed.")  # Shows progress of program
        if counter == image_count:  # Will stop program when counter reaches number of images
            break
    final_im = new_im.rotate(180, expand=1)  # stacking goes from top to bottom, rotate images at the end

    if outputdirectory is None:
        outputdirectory = directory
    final_im.save( os.path.join(outputdirectory, "stacked_image.tiff"), quality=95)

def main():
    # Convert coordinate list into variables
    print("Type in the coordinates for the upper left (x1,y1) and bottom right (x2,y2) points")
    coordinates = list(map(int, input("Separate values with a space (x1 y1 x2 y2): ").strip().split()))[:4]
    image_count = int(input("How many images are being stacked? "))
    print("Generating image...")

    process(directory, coordinates, image_count)

    print("Image completed and can be found in the output folder.")
    input("Press ENTER to close program.")  # prevents prompt from instantly closing

if __name__ == "__main__":
    main()
from tkinter import *
from tkinter import filedialog
from tkinter import messagebox
from PIL import Image
from natsort import natsorted
import glob
import gc

import imageprocess

# --- functions ---

def inputfile():
    master.inputdirectory = filedialog.askdirectory()
    print(master.inputdirectory)

def outputfile():
    master.outputdirectory = filedialog.askdirectory()
    print(master.outputdirectory)

def run():
    try:
        coordinates = [int(x1input.get()), int(x2input.get()), int(y1input.get()), int(y2input.get())]
        image_count = int(countinput.get())

        imageprocess.process(master.inputdirectory, coordinates, image_count, master.outputdirectory)

    except Exception as ex:
        print('ex:', ex)
        messagebox.showwarning("Warning", "Wrong arguments:\n" + str(ex))

# --- main ---

master = Tk()

master.inputdirectory = None   # default value at start
master.outputdirectory = None  # default value at start

master.title("One Dimensional Reaction Diffusion Program")
master.geometry("440x270")

header1 = Label(master, text="One Dimensional Reaction Diffusion Program\n"
                             "Created by: Alexander Tang\n")

header1.grid(sticky="N", columnspan=8)
instructions = Label(master, text="Type in the coordinates for the upper left (x1,y1) and bottom right (x2,y2) points:")
instructions.grid(sticky="W", columnspan=8)

x1 = Label(master, text="x1: ")
x1.grid(sticky="E", column=0, row=2)
x1input = Entry(master, width=5)
x1input.grid(sticky="W", column=1, row=2)

y1 = Label(master, text="y1: ")
y1.grid(sticky="E", column=2, row=2)
y1input = Entry(master, width=5)
y1input.grid(sticky="W", column=3, row=2)

x2 = Label(master, text="x2: ")
x2.grid(sticky="E", column=4, row=2)
x2input = Entry(master, width=5)
x2input.grid(sticky="W", column=5, row=2)

y2 = Label(master, text="y2: ")
y2.grid(sticky="E", column=6, row=2)
y2input = Entry(master, width=5)
y2input.grid(sticky="W", column=7, row=2, pady=12)

count = Label(master, text="How many images are being stacked? ")
count.grid(sticky="W", column=0, row=4, columnspan=4)
countinput = Entry(master, width=5)
countinput.grid(stick="W", column=5, row=4, pady=3)

step1 = Label(master, text="1. Select the file location: ")
step1.grid(sticky="W", column=0, row=6, columnspan=4)
step2 = Label(master, text="2. Select the save location: ")
step2.grid(sticky="W", column=0, row=7, columnspan=4)

btn_input = Button(master, text="Input Files", command=inputfile)
btn_input.grid(column=5, row=6, columnspan=2, pady=6)

btn_output = Button(master, text="Output Location", command=outputfile)
btn_output.grid(column=5, row=7, columnspan=2)

btn_run = Button(master, text="Run", font="Helvetica, 18", bg="blue", fg="white", command=run)
btn_run.grid(sticky="S", column=5, row=8, columnspan=2, pady=6)

mainloop()

它需要检查小部件中的值,并在参数错误时显示带有警告的窗口。但代码开始工作

它必须是
command=inputfile
中的函数名,而不是字符串
“inputfile”
将原始代码(处理图像)放入函数中,然后按钮可以运行它。如果您不将其放入函数中,则
import
将在开始时运行此代码-它不会等待GUI。不要在此代码中使用
input()
。如果您想在没有GUI的情况下运行它,那么您可以使用
If uuuuu name_uuuuu=='uuuuuu main_uuu':coordinates=input();你的函数(坐标);输入(“按ENTER键”)
您甚至应该将目录作为参数-
您的函数(坐标,目录)